var ISW,ZUtility;(function(ISW){var ShoppingCart=function(){function ShoppingCart(){this.ID=-1;this.DefaultCountryId=0;this.CartRequestId="";this.TotalDue=-1;this.Discount=null;this.GiftCertificates=[];this.DiscountTotal=0;this.TaxAmount=0;this.ShippingAmount=0;this.CanCheckout=!1;this.ValidationMessage="";this.Items=[];ShoppingCart._cartApiEventsRegistered||(ShoppingCart._cartApiEventsRegistered=!0,ShoppingCart._registerCartApiEvents())}return ShoppingCart.prototype._handleModifyCart=function(data){ISS.log("Handling cart action: "+data.Action+(data.Action=="RemoveAtIndex"?"; Index: "+data.Index:""));var tQuantity=data.hasOwnProperty("Quantity")?data.Quantity:1,saveToServer=data.hasOwnProperty("SaveToServer")?data.SaveToServer:!0;switch(data.Action){case"Add":this.addItem(new ISW.ShoppingCartItem(data.Product,tQuantity,data.ProductStyleId,data.ProductStyleSizeId),saveToServer);break;case"RemoveAtIndex":this.removeItemAtIndex(data.Index,saveToServer);break;case"SetQuantityAtIndex":this.setItemQuantityAtIndex(data.Index,tQuantity,saveToServer);break;case"ChangeSizeAtIndex":this.changeSizeAtIndex(data.Index,data.ProductStyleSizeId,saveToServer);break;case"ChangeStyleAtIndex":this.changeStyleAtIndex(data.Index,data.ProductStyleId,saveToServer);break;case"SetPersonalizationValueAtIndex":this.setItemPersonalizationValueAtIndex(data.Index,data.Name,data.Value,saveToServer)}},ShoppingCart.prototype.handleProductLoaded=function(data){var tItem,i;for(ISS.log("Product Data Loaded.  Updating Cart. Product ID: "+data.ID),i=0;i<this.Items.length;i++)tItem=this.Items[i],ISS.log("comparing IDs: "+tItem.ProductId+" : "+data.ID),tItem.ProductId==data.ID&&(ISS.log("target found."),this.Items[i]=ShoppingCartItem.parseFromJsonObject(tItem),ISS.log("target updated."));ISW.Messaging.instance.publish("CartUpdated",{Action:"ProductDataUpdated"})},ShoppingCart.getItemSubtotal=function(item){var rVal=0,mySize;if(item!=null)if(mySize=ISW.Product.GetProductStyleSizeById(item.Product,item.ProductStyleSizeId),mySize!=null)try{rVal=item.getTotal()}catch(ex){ISS.log("Error computing item subtotal.  Ex: "+ex.description)}else ISS.log("Error computing item subtotal: "+JSON.stringify(item));return rVal},ShoppingCart.prototype.containsCustomPersonalization=function(){for(var rVal=!1,i=0;i<this.Items.length;i++)if(this.Items[i].Product.PersonalizationType.toLowerCase()=="custom"){rVal=!0;break}return rVal},ShoppingCart.prototype.getSubtotalByProductId=function(id){var rVal=0,i;if(id!=null)for(i=0;i<this.Items.length;i++)this.Items[i]!=null&&this.Items[i].Product.ID==id&&(rVal+=this.Items[i].getTotal());return rVal},ShoppingCart.prototype.addAnotherProduct=function(saveToServer){var i,newItem;saveToServer===void 0&&(saveToServer=!1);ISS.log("Add Another Product");var itemToClone=this.Items[this.Items.length-1],p=itemToClone.Product,pStyle=Product.GetProductStyleById(p,itemToClone.ProductStyleId),pSize=pStyle.Sizes[0],sizecollision=!0,styleIndex=0,styleEndIndex=0,sizeIndex=0,onlyOneStyle=p.Styles.length==1;if(onlyOneStyle)styleEndIndex=styleIndex+1;else for(i=0;i<p.Styles.length;i++)p.Styles[i].ID==pStyle.ID&&(styleIndex=i,styleEndIndex=i>0?i-1:p.Styles.length-1);while(styleIndex!=styleEndIndex&&sizecollision){for(pStyle=p.Styles[styleIndex],sizecollision=!0;sizecollision&&sizeIndex<pStyle.Sizes.length;){for(sizecollision=!1,pSize=pStyle.Sizes[sizeIndex],i=0;i<this.Items.length;i++)this.Items[i].ProductStyleSizeId==pSize.ID&&(sizecollision=this.Items[i].Quantity==0?!1:!0);sizeIndex++}if(styleIndex++,styleIndex>=p.Styles.length&&(styleIndex=0),sizeIndex=0,onlyOneStyle)break}sizecollision?ISW.ISS.log("All available items are in the cart."):(newItem=new ShoppingCartItem(p,1,pStyle.ID,pSize.ID),this.addItem(newItem,saveToServer))},ShoppingCart.prototype.isFull=function(){var rVal=this.Items.length>0,styleSizeMatchFound=!1,p,i,j,k;if(rVal)for(p=this.Items[this.Items.length-1].Product,i=0;i<p.Styles.length&&rVal;i++)for(j=0;j<p.Styles[i].Sizes.length&&rVal;j++){for(styleSizeMatchFound=!1,k=0;k<this.Items.length;k++)if(this.Items[k].ProductStyleId==p.Styles[i].ID&&this.Items[k].ProductStyleSizeId==p.Styles[i].Sizes[j].ID&&this.Items[k].Quantity>0){styleSizeMatchFound=!0;break}styleSizeMatchFound||(rVal=!1)}return rVal},ShoppingCart.prototype.getTotal=function(round){var i;round===void 0&&(round=!1);var rVal=-1,allPricesAreSet=!0,tProductStyleSize,myTotal=0,tItemSubtotal;for(i=0;i<this.Items.length&&allPricesAreSet;i++)try{this.Items[i].Product==null&&ISW.ISS.log("Unable to compute total: product is null");tProductStyleSize=ISW.Product.GetProductStyleSizeById(this.Items[i].Product,this.Items[i].ProductStyleSizeId);tProductStyleSize==null||tProductStyleSize.UnitPrice==null||tProductStyleSize<0||tProductStyleSize.UnitPrice<0?allPricesAreSet=!1:this.Items[i].Quantity>0&&(tItemSubtotal=this.Items[i].getTotal(),myTotal=ZUtility.Num.GetDecimal((tItemSubtotal*100+myTotal*100)/100))}catch(ex){ISW.ISS.log("Exception occured when computing total: "+ex.description);allPricesAreSet=!1;myTotal=0}if(allPricesAreSet)if(round){rVal=myTotal;var s=String(""+rVal),pIndex=s.indexOf("."),zIndex=-1;pIndex>=0&&s.indexOf("000000",pIndex+1)>0&&(zIndex=s.indexOf("000000",pIndex+1),zIndex>0&&(s=s.substring(0,zIndex),ISS.log("got one"),rVal=Number(s)));rVal=Math.ceil(rVal*100)/100}else ISS.log("no round: "+myTotal),rVal=myTotal;return rVal},ShoppingCart._registerCartApiEvents=function(){ISS.log("Messaging instance null? "+(ISW.Messaging.instance==null?"true":"false"));ISW.Messaging.instance.subscribe("ProductLoaded",function(topic,data){ISW.ApiWrapper.instance.service.Cart.handleProductLoaded(data)});ISW.Messaging.instance.subscribe("ModifyCart",function(topic,data){ISW.ApiWrapper.instance.service.Cart._handleModifyCart(data)});ISS.log("Cart API events registered")},ShoppingCart.parseFromJsonObject=function(tCart){var rVal=new ShoppingCart,tpp,i;if(tCart!=null&&tCart.Items!=null)for(rVal.CartRequestId=tCart.CartRequestId,rVal.DefaultCountryId=tCart.DefaultCountryId,rVal.Discount=tCart.Discount,rVal.GiftCertificates=tCart.GiftCertificates,rVal.DiscountTotal=tCart.DiscountTotal,rVal.ID=tCart.ID,rVal.TaxAmount=tCart.TaxAmount,rVal.TotalDue=tCart.TotalDue,rVal.ShippingAmount=tCart.ShippingAmount,rVal.CanCheckout=tCart.CanCheckout,rVal.ValidationMessage=tCart.ValidationMessage,rVal.hasOwnProperty("CartRequestId")&&rVal.CartRequestId!=null||(rVal.CartRequestId=""),i=0;i<tCart.Items.length;i++)tpp=ShoppingCartItem.parseFromJsonObject(tCart.Items[i]),tpp!=null&&rVal.Items.push(tpp);return rVal},ShoppingCart.prototype.getTotalQuantity=function(){for(var rVal=0,i=0;i<this.Items.length;i++)rVal+=Number(""+this.Items[i].Quantity);return rVal},ShoppingCart.prototype.getVisibleItemCount=function(){for(var rVal=0,i=0;i<this.Items.length;i++)this.Items[i].Quantity>0&&rVal++;return rVal},ShoppingCart.prototype.teamNameNumbersEnabled=function(){for(var rVal=!1,i=0;i<this.Items.length;i++)if(this.Items[i].Product.PersonalizationType.toLowerCase()=="namesnumbers"){rVal=!0;break}return rVal},ShoppingCart.prototype.containsOtherSizes=function(item){for(var rVal=!1,i=0;i<this.Items.length;i++)if(this.Items[i].ProductStyleId==item.ProductStyleId&&this.Items[i].Quantity>0&&this.Items[i].ProductStyleSizeId!=item.ProductStyleSizeId){rVal=!0;break}return rVal},ShoppingCart.prototype.changeSizeAtIndex=function(index,productStyleSizeId,saveToServer){var newItems,i;saveToServer===void 0&&(saveToServer=!0);var matchIndex=-1,matchExists=!1,oldItem=this.Items[index],newItem=null,p=oldItem.Product;if(newItem=new ShoppingCartItem(p,oldItem.Quantity,oldItem.ProductStyleId,productStyleSizeId,-1,-1,JSON.parse(JSON.stringify(oldItem.PersonalizationValues))),oldItem.ProductStyleSizeId!=productStyleSizeId){for(ISS.log("Attempting to change size from "+oldItem.ProductStyleSizeId+" to "+productStyleSizeId),i=0;i<this.Items.length;i++)ShoppingCartItem.areEqual(this.Items[i],newItem)&&(matchIndex=i,matchExists=!0,ISS.log("Match found in cart.  Match quantity: "+this.Items[i].Quantity+"; Quantity to be added: "+oldItem.Quantity),this.Items[i].Quantity=Number(""+this.Items[i].Quantity)+Number(""+oldItem.Quantity),newItem=this.Items[i]);for(matchExists||(matchIndex=this.Items.length),oldItem.Quantity=0,this.Items[index]=newItem,this.Items[matchIndex]=oldItem,newItems=[],i=0;i<this.Items.length;i++)this.Items[i].Quantity>0&&newItems.push(this.Items[i]);this.Items=newItems;ISW.ApiWrapper.instance.service.saveToLocalStorage("Cart");ISS.log("Removing old item from cart.  Index: "+matchIndex);ISW.Messaging.instance.publish("CartUpdated",{Action:"ItemSizeChanged",Index:index});saveToServer&&ISW.ApiWrapper.instance.service.saveCartItemsToServer()}},ShoppingCart.prototype.setItemPersonalizationValueAtIndex=function(index,name,value,saveToServer){saveToServer===void 0&&(saveToServer=!0);this.Items[index].PersonalizationValues[name]=value;ISW.Messaging.instance.publish("CartUpdated",{Action:"ItemPersonalizationValueUpdated",Index:index});ISW.ApiWrapper.instance.service.saveToLocalStorage("Cart");saveToServer&&ISW.ApiWrapper.instance.service.saveCartItemsToServer()},ShoppingCart.prototype.changeStyleAtIndex=function(index,productstyleid,saveToServer){var newItems,i;saveToServer===void 0&&(saveToServer=!0);var oldItem=this.Items[index],oldStyle,newStyle,newItem=null,p=oldItem.Product,oldSize,newSize,matchIndex=-1,matchExists=!1,oldQuantity=0;if(oldItem.ProductStyleId!=productstyleid){for(oldStyle=Product.GetProductStyleById(p,oldItem.ProductStyleId),newStyle=Product.GetProductStyleById(p,productstyleid),oldSize=Product.GetProductStyleSizeById(p,oldItem.ProductStyleSizeId),oldQuantity=oldItem.Quantity>0?oldItem.Quantity:1,oldItem.Quantity=0,newSize=Product.GetProductStyleSizeByName(p,productstyleid,oldSize.Name),newItem=new ShoppingCartItem(p,oldQuantity,productstyleid,newSize.ID,-1,-1,JSON.parse(JSON.stringify(oldItem.PersonalizationValues))),ISS.log("Attempting to change style ('"+oldStyle.Name+"' to '"+newStyle.Name+"') at cartIndex "+index),i=0;i<this.Items.length;i++)if(ShoppingCartItem.areEqual(this.Items[i],newItem)){ISW.ISS.log("Found new style/color item in cart.");this.Items[i].Quantity=oldQuantity;newItem=this.Items[i];matchIndex=i;matchExists=!0;break}for(matchIndex<0&&(matchIndex=this.Items.length),this.Items[index]=newItem,this.Items[matchIndex]=oldItem,newItems=[],i=0;i<this.Items.length;i++)this.Items[i].Quantity>0&&newItems.push(this.Items[i]);this.Items=newItems;ISW.ApiWrapper.instance.service.saveToLocalStorage("Cart");ISS.log("Removing old item from cart.  Index: "+matchIndex);ISW.Messaging.instance.publish("CartUpdated",{Action:"ItemStyleChanged",Index:index});saveToServer&&ISW.ApiWrapper.instance.service.saveCartItemsToServer()}},ShoppingCart.prototype.addItem=function(item,saveToServer){var isDuplicate,quantityToAdd,i;for(saveToServer===void 0&&(saveToServer=!0),isDuplicate=!1,i=0;i<this.Items.length;i++)if(this.Items[i].Product.ID==item.Product.ID&&this.Items[i].ProductStyleId==item.ProductStyleId&&this.Items[i].ProductStyleSizeId==item.ProductStyleSizeId){quantityToAdd=item.hasOwnProperty("Quantity")?Number(item.Quantity):1;this.Items[i].Quantity=Number(this.Items[i].Quantity)+Number(quantityToAdd);isDuplicate=!0;item=this.Items[i];break}isDuplicate||this.Items.push(item);ISW.ApiWrapper.instance.service.saveToLocalStorage("Cart");ISW.Messaging.instance.publish("CartUpdated",{Action:"ItemAdded"});saveToServer?(ISS.log("Item added to client-side cart.  Adding to server."),ISW.ApiWrapper.instance.service.saveCartItemsToServer()):ISS.log("Item added to client-side cart.  Not saving to server yet.")},ShoppingCart.prototype.removeItemAtIndex=function(index,saveToServer){var newItems,i;for(saveToServer===void 0&&(saveToServer=!0),newItems=[],i=0;i<this.Items.length;i++)i!=index&&this.Items[i].Quantity>0&&newItems.push(this.Items[i]);this.Items=newItems;ISW.ApiWrapper.instance.service.saveToLocalStorage("Cart");ISW.Messaging.instance.publish("CartUpdated",{Action:"ItemRemoved"});saveToServer&&ISW.ApiWrapper.instance.service.saveCartItemsToServer()},ShoppingCart.prototype.setItemQuantityAtIndex=function(index,quantity,saveToServer){saveToServer===void 0&&(saveToServer=!0);quantity<1?this.removeItemAtIndex(index):(this.Items[index].Quantity=quantity,ISW.Messaging.instance.publish("CartUpdated",{Action:"UpdateItemQuantity"}),ISW.ApiWrapper.instance.service.saveToLocalStorage("Cart"),saveToServer&&ISW.ApiWrapper.instance.service.saveCartItemsToServer())},ShoppingCart.prototype.setItemQuantity=function(productStyleSizeId,quantity){for(var i=0;i<this.Items.length;i++)if(this.Items[i].ProductStyleSizeId==productStyleSizeId){ISW.ApiWrapper.instance.service.Cart.setItemQuantityAtIndex(i,quantity);break}},ShoppingCart.prototype.getItemByProductStyleSize=function(productstylesizeid){var rVal,i;for(ISS.log("Getting item by prouductstylesize.  ProductStyleSizeId: "+productstylesizeid),i=0;i<this.Items.length;i++)if(this.Items[i].ProductStyleSizeId==productstylesizeid){rVal=this.Items[i];ISS.log("Item found.");break}return rVal},ShoppingCart._cartApiEventsRegistered=!1,ShoppingCart}(),ShoppingCartItem,ProductPersonalization,ProductStyleSize,ProductStyle,ProductCategory,Product,State,CreditCard,Country,Order,TaxRecord,Address,ShippingMethod,CheckoutPackage,ISS,ApiStatus,ApiWrapper;ISW.ShoppingCart=ShoppingCart;ShoppingCartItem=function(){function ShoppingCartItem(data,quantity,productstyleid,productstylesizeid,cartretailitemid,cartretailitemsizeid,personalizationValues){this.CartRetailItemSizeId=-1;this.UnitPrice=-1;this.FullName=null;this.PersonalizationValues={};var tProductStyle=ISW.Product.GetProductStyleById(data,productstyleid),tProductStyleSize=ISW.Product.GetProductStyleSizeById(data,productstylesizeid);this.Product=data;this.ProductId=data.ID;this.Quantity=quantity;this.ProductStyleId=productstyleid;this.ProductStyleSizeId=productstylesizeid;this.CartRetailItemId=cartretailitemid;this.CartRetailItemSizeId=cartretailitemsizeid;tProductStyle!=null&&tProductStyleSize!=null&&(this.FullName=this.Product.Name.replace("'","\\'")+" - "+tProductStyle.Name.replace("'","\\'")+" - "+tProductStyleSize.Name);personalizationValues!=null&&(this.PersonalizationValues=personalizationValues)}return ShoppingCartItem.prototype.getTotal=function(){var r=0,myStyle=Product.GetProductStyleById(this.Product,this.ProductStyleId),mySize=Product.GetProductStyleSizeById(this.Product,this.ProductStyleSizeId),productPersonalizations=[],i,p,pv;for(this.Product.Personalizations&&this.Product.Personalizations.length>0&&(productPersonalizations=this.Product.Personalizations),r+=mySize.UnitPrice,i=0;i<productPersonalizations.length;i++)(p=productPersonalizations[i],pv=this.PersonalizationValues,p.Price&&p.Price!=0)&&(p.Required||pv.hasOwnProperty(p.Name)&&pv[p.Name].trim().length>0)&&(r+=p.Price);return Math.round(this.Quantity*r*100)/100},ShoppingCartItem.areEqual=function(item1,item2){var item1Keys=[],item2Keys=[];for(var key in item1.PersonalizationValues)item1Keys.push(key);for(key in item2.PersonalizationValues)item2Keys.push(key);if(item1.ProductStyleSizeId!=item2.ProductStyleSizeId||item1Keys.length!=item2Keys.length)return!1;if(item1Keys.length==0)return!0;for(key in item1.PersonalizationValues)if(!item2.PersonalizationValues.hasOwnProperty(key)||item1.PersonalizationValues[key]!=item2.PersonalizationValues[key])return!1;return!0},ShoppingCartItem.prototype.getImageUrl=function(){return Product.GetProductImageUrl(this.Product,this.ProductStyleId)},ShoppingCartItem.prototype.getImageSrc=function(){return Product.GetProductImageSrc(this.Product,this.ProductStyleId)},ShoppingCartItem.prototype.getProductImageSrcTemplate=function(){return Product.GetProductImageSrcTemplate(this.Product,this.ProductStyleId)},ShoppingCartItem.parseFromJsonObject=function(tCartItem){var tProduct=ISW.ApiWrapper.instance.service._getProductFromCacheById(tCartItem.ProductId),tPersonalizationValues={};for(var key in tCartItem.PersonalizationValues)tPersonalizationValues[key]=tCartItem.PersonalizationValues[key];return new ShoppingCartItem(tProduct,tCartItem.Quantity,tCartItem.ProductStyleId,tCartItem.ProductStyleSizeId,tCartItem.CartRetailItemId,tCartItem.CartRetailItemSizeId,tPersonalizationValues)},ShoppingCartItem.ParseFromXml=function(inxml){var trVal={},rVal=[],attrs=ZUtility.ClientXml.GetXmlElementAttributes(inxml,"cart_retail_items "),myXml=inxml,productXml,rpattrs,productSizeXml,psattrs,tItem,crisXmls,startIndex,endDelimiter,endIndex,tString,i;for(productXml=ZUtility.ClientXml.GetXmlElement("retail_products",myXml),myXml=myXml.replace(productXml,""),rpattrs=ZUtility.ClientXml.GetXmlElementAttributes(productXml,"retail_products");rpattrs.product_id>0;){for(trVal.Product=ISW.ApiWrapper.instance.service._getProductFromCacheById(parseInt(rpattrs.product_id)),productSizeXml=ZUtility.ClientXml.GetXmlElement("cart_retail_item_sizes",productXml),endDelimiter="<\/cart_retail_item_sizes>",crisXmls=[];productSizeXml.indexOf("<cart_retail_item_sizes")>=0;)startIndex=productSizeXml.indexOf("<cart_retail_item_sizes"),endIndex=productSizeXml.indexOf(endDelimiter)+endDelimiter.length,tString=productSizeXml.substring(startIndex,endIndex),crisXmls.push(tString),productSizeXml=productSizeXml.replace(tString,"");for(i=0;i<crisXmls.length&&crisXmls[i].trim().length>0;i++)psattrs=ZUtility.ClientXml.GetXmlElementAttributes(crisXmls[i],"cart_retail_item_sizes"),ISS.log("Parsing size attributes: "+JSON.stringify(psattrs)),trVal.Quantity=parseInt(psattrs.quantity),trVal.ProductStyleId=parseInt(rpattrs.product_style_id),trVal.ProductStyleSizeId=parseInt(psattrs.product_style_size_id),trVal.CartRetailItemId=-1,trVal.CartRetailItemSizeId=parseInt(psattrs.cart_retail_item_size_id),trVal.UnitPrice=Number(psattrs.price),tItem=new ShoppingCartItem(trVal.Product,trVal.Quantity,trVal.ProductStyleId,trVal.ProductStyleSizeId,trVal.CartRetailItemId,trVal.CartRetailItemSizeId),tItem!=null&&rVal.push(tItem);productXml=ZUtility.ClientXml.GetXmlElement("retail_products",myXml);myXml=myXml.replace(productXml,"");rpattrs=ZUtility.ClientXml.GetXmlElementAttributes(productXml,"retail_products")}return rVal},ShoppingCartItem}();ISW.ShoppingCartItem=ShoppingCartItem;ProductPersonalization=function(){function ProductPersonalization(id,name,description,required){this.ID=id;this.Name=name;this.Description=description;this.Required=required}return ProductPersonalization}();ISW.ProductPersonalization=ProductPersonalization;ProductStyleSize=function(){function ProductStyleSize(id,sortorder,name,styleprice,upcharge,instock){this.ID=id;this.SortOrder=sortorder;this.Name=name;this.LongName=ProductStyleSize.GetSizeLongName(name);this.UnitPrice=ZUtility.Num.GetDecimal((styleprice*100+upcharge*100)/100);this.UpCharge=upcharge;this.InStock=instock;ISS.log("Constructor calculating size price.  styleprice("+styleprice+") + upcharge("+upcharge+") = "+this.UnitPrice)}return ProductStyleSize.GetFromShoppingCartItem=function(item){return ISW.Product.GetProductStyleSizeById(item.Product,item.ProductStyleSizeId)},ProductStyleSize.GetSizeLongName=function(sizename){var rVal=sizename;switch(sizename){case"S":rVal="Small";break;case"M":rVal="Medium";break;case"L":rVal="Large";break;case"XL":rVal="X Large";break;case"2XL":rVal="2X Large";break;case"3XL":rVal="3X Large"}return rVal},ProductStyleSize.ParseFromData=function(data){var myUnitPrice=data.UnitPrice,myUpCharge=data.UpCharge,myInStock=data.InStock;return(""+myUnitPrice*100).indexOf(".")>=0&&(myUnitPrice=ZUtility.Num.GetDecimal(myUnitPrice)),(""+myUpCharge*100).indexOf(".")>=0&&(myUpCharge=ZUtility.Num.GetDecimal(myUpCharge)),myUnitPrice=ZUtility.Num.GetDecimal((data.UnitPrice*100-data.UpCharge*100)/100),new ProductStyleSize(data.ID,data.SortOrder,data.Name,myUnitPrice,myUpCharge,myInStock)},ProductStyleSize}();ISW.ProductStyleSize=ProductStyleSize;ProductStyle=function(){function ProductStyle(){this.Sizes=[]}return ProductStyle.ParseFromData=function(data){var rVal=new ProductStyle,tSize,i;if(rVal.ID=data.ID,rVal.IsDefault=data.IsDefault,rVal.Name=data.Name,rVal.HtmlColor1=data.HtmlColor1,rVal.HtmlColor2=data.HtmlColor2,rVal.CanPrint=data.CanPrint,rVal.CanDigitalPrint=data.CanDigitalPrint,rVal.CanScreenPrint=data.CanScreenPrint,rVal.CanEmbroider=data.CanEmbroider,rVal.UnitPrice=data.UnitPrice,rVal.Price_Canvas=data.Price_Canvas,rVal.Price_Name=data.Price_Name,rVal.Price_Number=data.Price_Number,rVal.ImageWidth_Front=data.ImageWidth_Front,rVal.ImageWidth_Back=data.ImageWidth_Back,rVal.ImageHeight_Front=data.ImageHeight_Front,rVal.ImageHeight_Back=data.ImageHeight_Back,rVal.ImageFilePath_Front=data.ImageFilePath_Front,rVal.ImageFilePath_Back=data.ImageFilePath_Back,rVal.ImageFilePath_SleeveLeft=data.ImageFilePath_SleeveLeft,rVal.ImageFilePath_SleeveRight=data.ImageFilePath_SleeveRight,rVal.Sizes=[],rVal.UnitPrice*100%1>0&&(rVal.UnitPrice=Number(parseInt(""+Math.round(rVal.UnitPrice*100))/100)),data.Sizes!=null){for(i=0;i<data.Sizes.length;i++)tSize=ProductStyleSize.ParseFromData(data.Sizes[i]),tSize!=null&&rVal.Sizes.push(tSize);rVal.Sizes.sort(function(a,b){return a.SortOrder-b.SortOrder})}return rVal},ProductStyle.GetFromShoppingCartItem=function(item){return ISW.Product.GetProductStyleById(item.Product,item.ProductStyleId)},ProductStyle.ParseFromXml=function(inxml){var rVal=new ProductStyle,psAttributes=ZUtility.ClientXml.GetXmlElementAttributes(inxml,"product_styles"),i;rVal.ID=Number(psAttributes.product_style_id);rVal.IsDefault=psAttributes.is_default=="1";rVal.Name=psAttributes.color;rVal.HtmlColor1=psAttributes.html_color;rVal.HtmlColor2=psAttributes.html_color2;rVal.CanPrint=psAttributes.can_print=="1";rVal.CanDigitalPrint=psAttributes.can_digital_print=="1";rVal.CanScreenPrint=psAttributes.can_screen_print=="1";rVal.CanEmbroider=psAttributes.can_embroider=="1";rVal.UnitPrice=parseFloat(psAttributes.unit_price);rVal.Price_Canvas=parseFloat(psAttributes.canvas_price);rVal.Price_Name=parseFloat(psAttributes.name_price);rVal.Price_Number=parseFloat(psAttributes.number_price);rVal.ImageWidth_Front=parseFloat(psAttributes.image_width_front);rVal.ImageWidth_Back=parseFloat(psAttributes.image_width_back);rVal.ImageHeight_Front=parseFloat(psAttributes.image_height_front);rVal.ImageHeight_Back=parseFloat(psAttributes.image_height_back);var tSizeIds=[],tSizeSortOrders=[],tSizeNames=[],tUpCharges=[],tInStock=[];try{if(tSizeIds=psAttributes.sizeids.split(","),tSizeSortOrders=psAttributes.sortOrders.split(","),tSizeNames=psAttributes.sizes.split(","),"upcharges"in psAttributes)tUpCharges=psAttributes.upcharges.split(",");else for(tUpCharges=[],i=0;i<tSizeIds.length;i++)tUpCharges[i]=0;ISS.log("everything is okay so far");ISS.log(inxml)}catch(ex){ISS.log("Error: "+ex.description);ISS.log(inxml);tSizeIds=[];tSizeSortOrders=[];tSizeNames=[];tInStock=[]}for(ISS.log("Upcharges from XML: "+psAttributes.upcharges),ISS.log("Upcharges parsed: "+JSON.stringify(tUpCharges)),ISS.log("InStock parsed: "+JSON.stringify(tInStock)),i=0;i<tSizeIds.length;i++)rVal.Sizes[i]=new ProductStyleSize(Number(tSizeIds[i]),tSizeSortOrders[i],tSizeNames[i],rVal.UnitPrice,tUpCharges[i],tInStock[i]);return rVal.Sizes.sort(function(a,b){return a.SortOrder-b.SortOrder}),ISS.log("Sizes added"),rVal},ProductStyle}();ISW.ProductStyle=ProductStyle;ProductCategory=function(){function ProductCategory(){this.ProductIds=[]}return ProductCategory.ParseFromXml=function(inxml){var rVal=new ProductCategory,elXml=ZUtility.ClientXml.GetXmlElement("ProductList",inxml),attrs=ZUtility.ClientXml.GetXmlElementAttributes(elXml,"CS"),tps,tProductId,i;for(rVal.ID=Number(attrs.product_category_id),rVal.Name=attrs.category,tps=ZUtility.ClientXml.GetChildXmlElements(elXml),i=0;i<tps.length;i++)attrs=ZUtility.ClientXml.GetXmlElementAttributes(tps[i],"CS"),tProductId=Number(attrs.product_id),rVal.ProductIds.indexOf(tProductId)<0&&rVal.ProductIds.push(tProductId);return rVal},ProductCategory}();ISW.ProductCategory=ProductCategory;Product=function(){function Product(){this.DefaultStyleId=-1;this.Personalizations=[];this.Styles=[]}return Product.GetProductStyleById=function(p,productstyleid){for(var logString="Get product style by id. ProductId: "+p.ID+"; StyleId: "+productstyleid,rVal=null,i=0;i<p.Styles.length;i++)if(p.Styles[i].ID==productstyleid){rVal=p.Styles[i];break}return rVal==null&&ISS.log(logString+". Product style "+productstyleid+" not found.  Searched: "+JSON.stringify(p.Styles)),rVal},Product.GetProductStyleSizeById=function(p,productStyleSizeId){for(var j,rVal=null,i=0;i<p.Styles.length;i++)for(j=0;j<p.Styles[i].Sizes.length;j++)p.Styles[i].Sizes[j].ID==productStyleSizeId&&(rVal=p.Styles[i].Sizes[j]);return rVal==null&&ISS.log("Get product size by id.. Product size "+productStyleSizeId+" not found.  Searched: "+JSON.stringify(p.Styles)),rVal},Product.GetProductStyleSizeByName=function(p,productstyleid,sizename){for(var rVal=null,ps=ISW.Product.GetProductStyleById(p,productstyleid),i=0;i<ps.Sizes.length;i++)ps.Sizes[i].Name==sizename&&(rVal=ps.Sizes[i]);return rVal},Product.GetProductImageUrl=function(p,productstyleid){return ISW.ApiWrapper.instance.service.UseJitImages?Product.GetProductImageStaticUrl(p,productstyleid):Product.GetProductImageJitUrl(p,productstyleid)},Product.GetProductImageStaticUrl=function(p,productstyleid){return Product.GetProductImageStaticUrlTemplate(p,productstyleid).replace(/{side}/g,"Front")},Product.GetProductImageJitUrl=function(p,productstyleid){return Product.GetProductImageJitUrlTemplate(p,productstyleid).replace(/{side}/g,"Front")},Product.GetProductImageStaticUrlTemplate=function(p,productstyleid){var tProductStyle=ISW.Product.GetProductStyleById(p,productstyleid);return ISW.ApiWrapper.instance.service.ApiBaseUrl+"images/products/"+ZUtility.Page.StoreData("PublisherId")+"/products/"+p.Sku+"/"+ZUtility.Format.MVCFriendlyEncode(tProductStyle.Name)+"/{side}/500.png"},Product.GetProductImageJitUrlTemplate=function(p,productstyleid){var tProductStyle=ISW.Product.GetProductStyleById(p,productstyleid);return ISW.ApiWrapper.instance.service.ApiBaseUrl+ISW.ApiWrapper.instance.service.StoreUri+"/JITImage/"+p.Sku+"/"+ZUtility.Format.MVCFriendlyEncode(tProductStyle.Name)+"/{side}/null/500.png"},Product.GetProductImageSrcTemplate=function(p,productstyleid){var tProductStyle=ISW.Product.GetProductStyleById(p,productstyleid),primaryUrl=Product.GetProductImageStaticUrl(p,productstyleid),jitImageUrl=Product.GetProductImageJitUrl(p,productstyleid),jitUrlUsed=$("img[src='"+jitImageUrl+"']").length>0,rVal='src="'+(jitUrlUsed?jitImageUrl:primaryUrl)+'"';return jitUrlUsed||(rVal+=" onerror=\"this.onerror = null; this.src = '"+jitImageUrl+"';\""),rVal},Product.PreloadImages=function(p){for(var myStyles=p.Styles,imageArray=[],productImageUrl,i=0;i<myStyles.length;i++)productImageUrl=Product.GetProductImageStaticUrl(p,myStyles[i].ID),imageArray[imageArray.length]=productImageUrl.replace("{side}","front"),p.HasBack&&(imageArray[imageArray.length]=productImageUrl.replace("{side}","back")),p.HasThirdSide&&(imageArray[imageArray.length]=productImageUrl.replace("{side}","sleeveleft")),p.HasFourthSide&&(imageArray[imageArray.length]=productImageUrl.replace("{side}","sleeveright"));ZUtility.Page.PreloadImages(imageArray)},Product.GetProductImageSrc=function(p,productstyleid){return Product.GetProductImageSrcTemplate(p,productstyleid).replace(/{side}/g,"Front")},Product.ParseFromData=function(data){var rVal=new Product,tProductStyle,i;for(rVal.ID=data.ID,rVal.Manufacturer=data.Manufacturer,rVal.Sku=data.Sku,rVal.Name=data.Name,rVal.LongDescription=ZUtility.Format.HtmlDecode(data.LongDescription),rVal.DefaultStyleId=data.DefaultStyleId,rVal.ManufacturerImage_Wide=ISS.insertUrl(data.ManufacturerImage_Wide),rVal.ManufacturerImage_Square=ISS.insertUrl(data.ManufacturerImage_Square),rVal.ManufacturerImage_Tiny=ISS.insertUrl(data.ManufacturerImage_Tiny),rVal.CanPrint=data.CanPrint,rVal.CanDigitalPrint=data.CanDigitalPrint,rVal.CanScreenPrint=data.CanScreenPrint,rVal.CanEmbroider=data.CanEmbroider,rVal.CanHandleSleeves=data.CanHandleSleeves,rVal.TeamNameNumbersEnabled=data.TeamNameNumbersEnabled,rVal.HasBack=data.HasBack,rVal.HasThirdSide=data.HasThirdSide,rVal.HasFourthSide=data.HasFourthSide,rVal.ThirdSideName=data.ThirdSideName,rVal.FourthSideName=data.FourthSideName,rVal.IsStatic=data.IsStatic,rVal.Styles=[],rVal.SizeChartUrl=data.SizeChartUrl,rVal.PersonalizationType=data.PersonalizationType,rVal.Personalizations=data.Personalizations,rVal.AddToCartButtonText=data.AddToCartButtonText,i=0;i<data.Styles.length;i++)tProductStyle=ProductStyle.ParseFromData(data.Styles[i]),tProductStyle!=null&&rVal.Styles.push(tProductStyle);return rVal.DefaultStyleId<1&&rVal.Styles.length>0&&(rVal.DefaultStyleId=rVal.Styles[0].ID,rVal.Styles[0].IsDefault=!0),rVal},Product.ParseFromXml=function(inxml){var rVal=new Product,elXml=ZUtility.ClientXml.GetXmlElement("products",inxml),attrs=ZUtility.ClientXml.GetXmlElementAttributes(elXml,"products"),tps,tpsItem,i;for(rVal.ID=Number(attrs.product_id),rVal.Manufacturer=attrs.manufacturer,rVal.ManufacturerSku=attrs.manufacturer_sku,rVal.Sku=attrs.sku,rVal.Name=attrs.name,rVal.LongDescription=attrs.long_description,rVal.ManufacturerImage_Wide=ISS.insertUrl(attrs.mfr_image_wide),rVal.ManufacturerImage_Square=ISS.insertUrl(attrs.mfr_image_square),rVal.ManufacturerImage_Tiny=ISS.insertUrl(attrs.mfr_image_tiny),rVal.CanPrint=attrs.can_print=="1",rVal.CanDigitalPrint=attrs.can_digital_print=="1",rVal.CanScreenPrint=attrs.can_screen_print=="1",rVal.CanEmbroider=attrs.can_embroider=="1",rVal.CanHandleSleeves=attrs.can_handle_sleeves=="1",rVal.TeamNameNumbersEnabled=attrs.enable_team_name_Numbers=="1",rVal.HasBack=attrs.has_back=="1",rVal.HasThirdSide=attrs.has_third_side=="1",rVal.HasFourthSide=attrs.has_fourth_side=="1",rVal.ThirdSideName=attrs.third_side_name,rVal.FourthSideName=attrs.fourth_side_name,rVal.IsStatic=attrs.is_static=="1",rVal.SizeChartUrl=null,tps=ZUtility.ClientXml.GetChildXmlElements(elXml),i=0;i<tps.length;i++)tpsItem=ProductStyle.ParseFromXml(tps[i]),tpsItem!=null?(tpsItem.IsDefault&&(rVal.DefaultStyleId=tpsItem.ID),rVal.Styles.push(tpsItem)):ISS.log("null style: "+tps[i]);return rVal.DefaultStyleId<1&&rVal.Styles.length>0&&(rVal.DefaultStyleId=rVal.Styles[0].ID,rVal.Styles[0].IsDefault=!0),rVal},Product}();ISW.Product=Product;State=function(){function State(id,name,code,countryid){this.ID=id;this.Name=name;this.Code=code;this.CountryId=countryid}return State.getStatesByCountryId=function(states,countryid){for(var rVal=[],i=0;i<states.length;i++)states[i].CountryId==countryid&&rVal.push(states[i]);return rVal},State}();ISW.State=State;CreditCard=function(){function CreditCard(no,expMonth,expYear,cvv){this.Number=no;this.ExpirationMonth=expMonth;this.ExpirationYear=expYear;this.CVV=cvv}return CreditCard}();ISW.CreditCard=CreditCard;Country=function(){function Country(id,name,code){this.ID=id;this.Name=name;this.Code=code}return Country}();ISW.Country=Country;Order=function(){function Order(){this.ID=-1;this.CurrencyCode="USD";this.CurrencySymbol="$";this.GiftMessage="";this.IpAddress="";this.PaymentMethod="";this.BillingAddress=null;this.ShippingAddress=null;this.ShippingMethod=null;this.AmountDue=0;this.GiftCertificateAmount=0;this.ProcessAmount=0;this.ProcessMarkupAmount=0;this.QuantityDiscountAmount=0;this.QuantityDiscountPercent=0;this.RetailAmount=0;this.RetailDiscount=0;this.ShippingAmount=0;this.ShippingTax=0;this.TaxAmount=0;this.TaxRate=0;this.TotalAmount=0;this.TotalDiscount=0;this.ConfirmedShipDate=null;this.DateCreated=null;this.EstimatedDeliveryDate_Max=null;this.EstimatedDeliveryDate_Min=null;this.EstimatedShipDate=null;this.Authorized=!1;this.Cancelled=!1;this.Confirmed=!1;this.DisplayPricing=!1;this.Ordered=!1;this.Paid=!1;this.Prepared=!1;this.Received=!1;this.Shipped=!1;this.Items=[]}return Order.parseFromJsonObject=function(order){var rVal=order,tItems=order.Items,tpp,i;if(order!=null)for(rVal.Items=[],i=0;i<tItems.length;i++)tpp=ShoppingCartItem.parseFromJsonObject(tItems[i]),tpp!=null&&rVal.Items.push(tpp);return rVal},Order}();ISW.Order=Order;TaxRecord=function(){function TaxRecord(){}return TaxRecord.ParseFromData=function(data){var rVal=null;try{rVal.ID=data.ID;rVal.City=data.City;rVal.CitySalesTax=data.CitySalesTax;rVal.CityUseTax=data.CityUseTax;rVal.County=data.County;rVal.CountySalesTax=data.CountySalesTax;rVal.CountyUseTax=data.CountyUseTax;rVal.ShippingAndHandlingTaxable=data.ShippingAndHandlingTaxable;rVal.ShippingTaxable=data.ShippingTaxable;rVal.StateCode=data.StateCode;rVal.StateSalesTax=data.StateSalesTax;rVal.StateUseTax=data.StateUseTax;rVal.TaxRecordId=data.TaxRecordId;rVal.TotalSalesTax=data.TotalSalesTax;rVal.TotalUseTax=data.TotalUseTax;rVal.ZipCode=data.ZipCode}catch(ex){}return rVal},TaxRecord}();ISW.TaxRecord=TaxRecord;Address=function(){function Address(){this.IsPoBox=!1;this.IsBusiness=!1;this.FirstName="";this.LastName="";this.Street1="";this.Street2="";this.City="";this.StateId=1;this.CountryId=1;this.Zip="";this.Phone=""}return Address.IsMatch=function(a,b){var rVal=!1;return JSON.stringify(a)==JSON.stringify(b)&&(rVal=!0),rVal},Address.IsComplete=function(a){var rVal=!1,countryStateValid=a.CountryId>=0,stateList=[];return countryStateValid&&(stateList=State.getStatesByCountryId(ApiWrapper.instance.service.BillingStateList,a.CountryId),countryStateValid==a.StateId>=0||stateList.length==0),a.FirstName.length>0&&a.LastName.length>0&&a.Street1.length>0&&a.City.length>0&&a.CountryId>=0&&countryStateValid&&a.Zip.length>0&&(rVal=!0),rVal},Address.ParseFromXml=function(inxml){var rVal=null,elXml=ZUtility.ClientXml.GetXmlElement("addresses",inxml),attrs=ZUtility.ClientXml.GetXmlElementAttributes(elXml,"addresses");try{rVal=new Address;rVal.ID=parseInt(attrs.address_id);rVal.IsPoBox=attrs.pobox=="1";rVal.IsBusiness=attrs.business=="1";rVal.CacheId=-1;rVal.FirstName=attrs.first_name;rVal.LastName=attrs.last_name;rVal.Street1=attrs.street1;rVal.Street2=attrs.street2;rVal.City=attrs.city;rVal.StateId=parseInt(attrs.state_id);rVal.CountryId=parseInt(attrs.country_id);rVal.Zip=attrs.postcode;rVal.Phone=attrs.phone}catch(ex){ISS.log("Error parsing shipping method: "+ex.description+"; xml: "+inxml)}return rVal},Address}();ISW.Address=Address;ShippingMethod=function(){function ShippingMethod(){}return ShippingMethod.GetLoadedById=function(id){for(var rVal=null,smList=ISW.ApiWrapper.instance.service.ShippingMethods,i=0;i<smList.length&&rVal==null;i++)smList[i].ID==id&&(rVal=smList[i]);return rVal},ShippingMethod.ParseFromXml=function(inxml){var rVal=null,elXml=ZUtility.ClientXml.GetXmlElement("shipping_method",inxml),attrs=ZUtility.ClientXml.GetXmlElementAttributes(elXml,"shipping_method");try{rVal=new ShippingMethod;rVal.ID=Number(attrs.shipping_method_id);rVal.Name=attrs.name;rVal.Vendor=attrs.vendor;rVal.VendorType=attrs.vendor_type;rVal.Name=attrs.name;rVal.DisableShippingAddress=attrs.disable_shipping_address;rVal.Price=parseFloat(attrs.price);rVal.MinDays=Number(attrs.min_days);rVal.MaxDays=Number(attrs.max_days);rVal.ProcessDays=Number(attrs.process_days);rVal.EstimatedMessage=attrs.estimated_delivery}catch(ex){ISS.log("Error parsing shipping method: "+ex.description+"; xml: "+inxml)}return rVal},ShippingMethod.ParseListFromXml=function(inxml){for(var rVal=[],elXml=ZUtility.ClientXml.GetXmlElement("shipping_methods",inxml),tps=ZUtility.ClientXml.GetChildXmlElements(elXml),t,i=0;i<tps.length;i++)t=ShippingMethod.ParseFromXml(tps[i]),t!=null&&rVal.push(t);return rVal},ShippingMethod}();ISW.ShippingMethod=ShippingMethod;CheckoutPackage=function(){function CheckoutPackage(){this.BillingAddress=new Address;this.ShippingAddress=new Address;this.ShippingMethodId=317;this.Email="";this.ccNum="";this.ccExpMonth=1;this.ccExpYear=(new Date).getFullYear();this.ccCVV="";this.PoNum="";this.PaymentMethod="Credit Card";this.GiftMessage="";this.TaxRate=0;this.BillingZipMismatch=!1;this.ShippingZipMismatch=!1}return CheckoutPackage}();ISW.CheckoutPackage=CheckoutPackage;ISS=function(){function ISS(){var ca,ct,i,myArray;this.StoreDNSName="";this.ApiBaseUrl="";this.Api2BaseUrl="";this.StoreId=-1;this.StoreUri="";this.Cart=null;this.CartRequestId="";this.InitStep=0;this.SubmitTransactionStep=0;this.IsInitializing=!1;this.IsSubmittingTransaction=!1;this.UseJitImages=!0;this.ProductCache=[];this.ProductCategoryCache=[];this.BillingStateList=[];this.ShippingStateList=[];this.BillingCountryList=[];this.ShippingCountryList=[];this.ShippingMethods=[];this.PaymentMethods=[];this.StoreLastUpdatedUtc=null;this.ProductCacheLastUpdatedUtc=new Date(Date.UTC(1900,1,1));this.CheckoutPackage=new CheckoutPackage;this.SupportsLocalStorage=!1;this.SaveCartTimer=null;this.CartIsSaving=!1;this.SaveCartOnSaveReturn=!1;this.CartSaveRetryCount=0;this.CartSaveRetryLimit=3;this.GetServerTotalsOnSaveCartReturn=!1;ISS.log("ISS Constructor Start.  Detecting local storage support.");try{localStorage.Test="test";localStorage.Test=="test"&&(this.SupportsLocalStorage=!0)}catch(ex){}if(this.SupportsLocalStorage?ISS.log("Local storage is supported."):ISS.log("Local storage is not supported."),ca=document.cookie.split(";"),ZUtility.Page.RequestVal("StoreUri").length>0&&(this.StoreUri=ZUtility.Page.RequestVal("StoreUri"),this.StoreId=-1),$("StoreData").length>0&&(ISS.log("Reading StoreId, StoreLastUpdatedUtc, and InkSoftApiBaseUrl from HTML... "),this.StoreUri=ZUtility.Page.StoreData("StoreUri"),this.StoreId=parseInt(ZUtility.Page.StoreData("StoreId")),this.StoreLastUpdatedUtc=new Date(ZUtility.Page.StoreData("StoreLastUpdatedUtc")),this.StoreDNSName=ZUtility.Page.StoreData("StoreDNSName"),this.ApiBaseUrl=document.location.protocol+"//"+document.location.host,this.Api2BaseUrl=this.ApiBaseUrl+"/"+this.StoreUri+"/Api2/",this.UseJitImages=ZUtility.Page.StoreData("UseJitImages").toLowerCase()!="false",ISS.log("UseJitImages: "+this.UseJitImages),ISS.log("Information parsed from HTML.  Store ID: "+this.StoreId+"; StoreName: "+this.StoreUri+"; ApiBaseUrl : "+this.ApiBaseUrl)),this.StoreId<0)for(ISS.log("Reading StoreId, StoreLastUpdatedUtc, and InkSoftApiBaseUrl from cookie: "+document.cookie),i=0;i<ca.length;i++)ct=ca[i].trim(),ct.toLowerCase().indexOf("storeid_"+this.StoreUri.toLowerCase())==0&&(myArray=ct.split("="),$("StoreData").length>0?(this.StoreUri=$("StoreData").attr("StoreUri"),this.StoreId=parseInt($("StoreData").attr("StoreId"))):(this.StoreUri=myArray[0].replace("StoreId_",""),this.StoreId=Number(myArray[1]))),ct.indexOf("StoreLastUpdatedUtc_"+this.StoreUri)==0&&(ISS.log("Found StoreLastUpdatedUtc in cookie: "+ct),this.StoreLastUpdatedUtc=new Date(ct.split("=")[1]));this.ApiBaseUrl[this.ApiBaseUrl.length-1]!="/"&&(this.ApiBaseUrl+="/")}return ISS.log=function(m){ISS.LogOutput&&console.log(m)},ISS.prototype._checkSSL=function(){var locString=document.location.toString().toLowerCase(),newLoc;if(ISW.ISS.log("Checking for secure connection"),locString.indexOf("http://")==0&&locString.indexOf("secure=1")<0){ISW.ISS.log("insecure connection detected.");var sslDomain=ZUtility.Page.StoreData("SSL_Domain").toLowerCase(),sslDomainMatches=sslDomain.length>0&&locString.indexOf(sslDomain)>0,isInkSoftDomain=locString.indexOf("inksoft.com")>0,safeToRedirect=sslDomainMatches||isInkSoftDomain;sslDomainMatches||isInkSoftDomain||(safeToRedirect=!1);safeToRedirect?(newLoc=document.location.toString().replace("http://","https://"),newLoc+=newLoc.indexOf("?")<0?"?":"&",newLoc+="Secure=1",ISW.ISS.log("Redirecting.  New location: "+newLoc),window.open(newLoc,"_self")):ISW.ISS.log("not safe to redirect.")}},ISS.prototype._initialize=function(){this.InitStep++;var startTicks=(new Date).getTime();switch(this.InitStep){case 1:ISS.log("Step 0.5: Check SSL. "+((new Date).getTime()-startTicks)+" ms");this._checkSSL();ISS.log("Step 1: Load from cookie. "+((new Date).getTime()-startTicks)+" ms");this.loadFromLocalStorage(!0);break;case 2:ISS.log("Step 2: Establish session. "+((new Date).getTime()-startTicks)+" ms");this._establishSession();break;case 3:ISS.log("Step 3: Core initialized.  Ready to load widgets.");ISW.ApiWrapper.onLoadComplete();this._initialize();break;case 4:ISS.log("Step 4: Establish cart. "+((new Date).getTime()-startTicks)+" ms");this._establishCart();break;case 5:ISS.log("Step 5: Getting Payment Methods. "+((new Date).getTime()-startTicks)+" ms");this.getPaymentMethods();break;case 6:ISS.log("Step 6: Save to cookie. "+((new Date).getTime()-startTicks)+" ms");this.saveToLocalStorage("",!0);break;default:ISS.log("Initialized. "+((new Date).getTime()-startTicks)+" ms")}},ISS.insertUrl=function(val){var rVal="";return val!=null&&(rVal=val.replace("REPLACE_DOMAIN_WITH",ISW.ApiWrapper.instance.service.ApiBaseUrl)),rVal},ISS.prototype._handleFailure=function(){ISS.log("ISS Failure.")},ISS.prototype._establishSession=function(){var tSessionId=ZUtility.Page.RequestVal("SessionId"),tSessionToken=ZUtility.Page.RequestVal("SessionToken");tSessionId.length>0&&tSessionToken.length>0&&(ISS.log("Session info found in query string."),this.SessionId=tSessionId,this.SessionToken=tSessionId);this.SessionId!=null&&this.SessionId!=""&&this.SessionId.indexOf("<Error")<0?(ISS.log("Session verified.  In cookie."),this._initialize(),this._handleSessionEstablished()):(ISS.log("Session not found in cookie.  must get from server."),this._createNewSession())},ISS.prototype._handleSessionEstablished=function(){if(this.SessionId!=null&&this.SessionId.length>0&&this.SessionToken!=null&&this.SessionToken.length>0){var o={};o.SessionId=ISW.ApiWrapper.instance.service.SessionId;o.SessionToken=ISW.ApiWrapper.instance.service.SessionToken;ISW.Messaging.instance.publish("SessionEstablished",o)}},ISS.prototype._establishCart=function(){this.Cart!=null?(ISS.log("Cart verified.  In local storage."),ISW.Messaging.instance.publish("CartLoaded",ISW.ApiWrapper.instance.service.Cart),this._initialize()):this._loadCartFromServer(function(){ISW.Messaging.instance.publish("CartLoaded",ISW.ApiWrapper.instance.service.Cart);ApiWrapper.instance.service._initialize();ApiWrapper.instance.service.loadStateList();ApiWrapper.instance.service.loadStateList(!0);ApiWrapper.instance.service.loadCountryList();ApiWrapper.instance.service.loadCountryList(!0)})},ISS.prototype.getPaymentMethods=function(){var myUrl=this.ApiBaseUrl;myUrl+="GetCartPaymentMethods/"+this.StoreId+"/"+this.SessionId;myUrl+="/1";ISS.log("Getting payment methods from server.");this._ajaxS(myUrl,function(res){var pmList=[],elXml,tps,i;for(ISS.log("Payment method response: "+res),elXml=ZUtility.ClientXml.GetXmlElement("payment_methods",res),ISS.log("elXml: "+elXml),tps=ZUtility.ClientXml.GetChildXmlElements(elXml),i=0;i<tps.length;i++)ISS.log("Item: "+tps[i]),pmList.push(ZUtility.ClientXml.GetXmlElementContent("payment_method",tps[i]));ISW.ApiWrapper.instance.service.PaymentMethods=pmList;ISS.log("Payment methods loaded from server: "+JSON.stringify(pmList));ISW.Messaging.instance.publish("PaymentMethodsLoaded",pmList);ISW.ApiWrapper.instance.service._initialize()},function(jqXHR,textStatus,ex){ISW.ISS.log("Warning: No payment methods are available for this store: "+ex);ISW.Messaging.instance.publish("PaymentMethodsLoaded",[]);ISW.ApiWrapper.instance.service._initialize()})},ISS.removeCookie=function(cname){document.cookie=cname+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT"},ISS.getObjectCookie=function(cname){for(var c,rVal=null,name=cname+"=",ca=document.cookie.split(";"),i=0;i<ca.length;i++)if(c=ca[i].trim(),c.indexOf(name)==0){rVal=c.substring(name.length,c.length);try{rVal=JSON.parse(rVal)}catch(ex){alert("Unable to parse cookie.  "+ex.description);this.removeCookie("IswData_"+ISW.Util.getStoreUri())}}return rVal},ISS.setObjectCookie=function(cname,obj){var d=new Date,expString,tString;d.setTime(d.getTime()+6048e5);expString="expires="+d.toUTCString();tString=cname+"="+JSON.stringify(obj)+"; "+expString;document.cookie=tString;ISS.log("Cookie saved.")},ISS.removeLocalStorage=function(){try{localStorage.ProductCache=[];localStorage.ProductCategoryCache=[];localStorage.BillingStateList=[];localStorage.BillingCountryList=[];localStorage.ShippingMethods=[];localStorage.CheckoutPackage=null}catch(ex){}},ISS.prototype.loadFromLocalStorage=function(initOnComplete){var c,tProduct,tStateList,tCountryList,hasA,i;try{c=ISS.getObjectCookie("IswData_"+ISW.Util.getStoreUri());ISS.log("Attempting to load data from cookie");c!=null?(this.SessionId=c.SessionId,this.SessionToken=c.SessionToken,ISS.log("Data loaded from cookie.  SessionId: "+this.SessionId+"; SessionToken: "+c.SessionToken)):ISS.log("Cookie is null or not present.");ISS.log("Attempting to load data from local storage");var tString="",ts="",tpa=[];if($("script[type=product-data]").length==1&&(ts=$("script[type=product-data]").html(),String(""+ts).length>100&&eval("tpa = "+ts)),ISS.log("Loading product cache from preloaded data.  TPA Length = "+tpa.length),tpa.length>0){for(ISS.log("Loading product cache from preloaded data."),i=0;i<tpa.length;i++)tProduct=Product.ParseFromData(tpa[i]),ISS.log("Product price: "+tProduct.Styles[tProduct.Styles.length-1].UnitPrice),this._addToProductCache(tProduct,!0);this._initSizeCharts()}if(this.SupportsLocalStorage){if(tString=localStorage.ProductCategoryCache,localStorage.ProductCategoryCache!=null&&tString.length>0?(this.ProductCategoryCache=JSON.parse(tString),ISS.log("Product Category data loaded from product cache")):ISS.log("Product Category cache contains no data."),tString=localStorage.BillingStateList,localStorage.BillingStateList!=null&&tString.length>0){tStateList=JSON.parse(tString);try{if(tString.indexOf("undefined")<0){for(hasA=!0,i=0;i<tStateList.length&&!hasA;i++)if(!tStateList[i].hasOwnProperty("Name")){hasA=!1;break}tStateList.length<1&&(hasA=!1);hasA?(this.BillingStateList=tStateList,ISW.Messaging.instance.publish("BillingStateListLoaded",this.BillingStateList),ISS.log("Billing State list loaded from cache")):this.BillingStateList=[]}}catch(ex){this.BillingStateList=[]}}if(this.BillingStateList.length<1&&(ISS.log("Billing State list not cached locally.  Loading from server"),this.loadStateList()),tString=localStorage.ShippingStateList,localStorage.ShippingStateList!=null&&tString.length>0){tStateList=JSON.parse(tString);try{if(tString.indexOf("undefined")<0){for(hasA=!0,i=0;i<tStateList.length&&!hasA;i++)if(!tStateList[i].hasOwnProperty("Name")){hasA=!1;break}tStateList.length<1&&(hasA=!1);hasA?(this.ShippingStateList=tStateList,ISW.Messaging.instance.publish("ShippingStateListLoaded",this.ShippingStateList),ISS.log("Shipping State list loaded from cache")):this.ShippingStateList=[]}}catch(ex){this.ShippingStateList=[]}}if(this.ShippingStateList.length<1&&(ISS.log("Shipping State list not cached locally.  Loading from server"),this.loadStateList(!0)),tString=localStorage.BillingCountryList,localStorage.BillingCountryList!=null&&tString.length>0){tString=localStorage.BillingCountryList;tCountryList=JSON.parse(tString);try{if(tString.indexOf("undefined")<0){for(hasA=!0,i=0;i<tCountryList.length&&!hasA;i++)if(!tCountryList[i].hasOwnProperty("Name")){hasA=!1;break}tCountryList.length<1&&(hasA=!1);hasA?(this.BillingCountryList=tCountryList,ISW.Messaging.instance.publish("BillingCountryListLoaded",this.BillingCountryList),ISS.log("Billing Country list loaded from cache.")):this.BillingCountryList=[]}}catch(ex){this.BillingCountryList=[]}}if(this.BillingCountryList.length<5&&(ISS.log("Billing Country list not cached locally.  Loading from server."),this.loadCountryList()),tString=localStorage.ShippingCountryList,localStorage.ShippingCountryList!=null&&tString.length>0){tString=localStorage.ShippingCountryList;tCountryList=JSON.parse(tString);try{if(tString.indexOf("undefined")<0){for(hasA=!0,i=0;i<tCountryList.length&&!hasA;i++)if(!tCountryList[i].hasOwnProperty("Name")){hasA=!1;break}tCountryList.length<1&&(hasA=!1);hasA?(this.ShippingCountryList=tCountryList,ISW.Messaging.instance.publish("ShippingCountryListLoaded",this.ShippingCountryList),ISS.log("Shipping Country list loaded from cache.")):this.ShippingCountryList=[]}}catch(ex){this.ShippingCountryList=[]}}this.ShippingCountryList.length<1&&(ISS.log("Shipping Country list not cached locally.  Loading from server."),this.loadCountryList(!0));tString=localStorage.ShippingMethods;localStorage.ShippingMethods!=null&&tString.length>0?(tString=localStorage.ShippingMethods,this.ShippingMethods=JSON.parse(tString),ISW.Messaging.instance.publish("ShippingMethodsLoaded",this.ShippingMethods),ISS.log("ShippingMethods loaded from cache.")):(ISS.log("ShippingMethods not cached locally.  Loading from server."),this.loadShippingMethods());tString=localStorage.CheckoutPackage;localStorage.CheckoutPackage!=null&&tString.length>0&&tString!="null"?(tString=localStorage.CheckoutPackage,this.CheckoutPackage=JSON.parse(tString),this.CheckoutPackage.BillingAddress==null||this.CheckoutPackage.BillingAddress.FirstName==null?(this.CheckoutPackage=new CheckoutPackage,ISW.Messaging.instance.publish("CheckoutPackageLoaded",this.CheckoutPackage),ISS.log("CheckoutPackage in cache was null.  Created new.")):(ISW.Messaging.instance.publish("CheckoutPackageLoaded",this.CheckoutPackage),ISS.log("CheckoutPackage loaded from cache."))):ISS.log("CheckoutPackage not cached locally.  Loading from server.");ISS.log("3")}else ISS.log("Local storage is not supported.  Loading state and country lists from server"),this.loadStateList(),this.loadStateList(!0),this.loadCountryList(),this.loadCountryList(!0),this.loadShippingMethods();initOnComplete!=null&&this._initialize()}catch(ex){this._handleFailure()}},ISS.prototype._addToProductCache=function(product,setCacheLastUpdatedUtc){var existsInCache=!1,i;for(setCacheLastUpdatedUtc&&(this.ProductCacheLastUpdatedUtc=ISW.Util.getUTCNow()),i=0;i<this.ProductCache.length;i++)if(this.ProductCache[i].ID==product.ID){existsInCache=!0;this.ProductCache[i]=product;break}existsInCache||(this.ProductCache.push(product),this.saveToLocalStorage("ProductCache"))},ISS.prototype._addToProductCategoryCache=function(pc){for(var existsInCache=!1,i=0;i<this.ProductCategoryCache.length;i++)if(this.ProductCategoryCache[i].ID==pc.ID){existsInCache=!0;this.ProductCategoryCache[i]=pc;break}existsInCache||(this.ProductCategoryCache.push(pc),this.saveToLocalStorage("ProductCategoryCache"))},ISS.prototype.saveToLocalStorage=function(specificItem,initOnComplete){specificItem===void 0&&(specificItem="");try{if(ISS.setObjectCookie("IswData_"+ISW.Util.getStoreUri(),{SessionId:this.SessionId,SessionToken:this.SessionToken}),this.SupportsLocalStorage&&(ISS.log("Saving to local storage"),this.ProductCache.length>0&&(specificItem==""||specificItem=="ProductCache")&&(localStorage.ProductCacheLastUpdatedUtc=this.ProductCacheLastUpdatedUtc.toString(),localStorage.ProductCache=JSON.stringify(this.ProductCache)),this.ProductCategoryCache.length>0&&(specificItem==""||specificItem=="ProductCategoryCache")&&(localStorage.ProductCategoryCache=JSON.stringify(this.ProductCategoryCache)),this.BillingStateList.length>0&&(specificItem==""||specificItem=="StateList")&&(localStorage.StateList=JSON.stringify(this.BillingStateList)),this.BillingCountryList.length>0&&(specificItem==""||specificItem=="CountryList")&&(localStorage.CountryList=JSON.stringify(this.BillingCountryList)),this.ShippingCountryList.length>0&&(specificItem==""||specificItem=="ShippingCountryList")&&(localStorage.ShippingCountryList=JSON.stringify(this.ShippingCountryList)),this.ShippingMethods.length>0&&(specificItem==""||specificItem=="ShippingMethods")&&(localStorage.ShippingMethods=JSON.stringify(this.ShippingMethods)),this.CheckoutPackage!=null&&(specificItem==""||specificItem=="CheckoutPackage"))){var tcp=this.CheckoutPackage;tcp.ccCVV="";tcp.ccNum="";localStorage.CheckoutPackage=JSON.stringify(tcp);ISS.log("CheckoutPackage Saved")}initOnComplete!=null&&initOnComplete==!0&&this._initialize()}catch(ex){ISS.log("An error occcured when saving ISS to cookie.");this._handleFailure()}},ISS.prototype._createNewSession=function(){ISS.log("Getting new session from server...");var myUrl=this.ApiBaseUrl+"GetNewSession/"+this.StoreId;this._ajaxS(myUrl,function(res){try{ISS.log("Got Session from server. res: "+res);ISW.ApiWrapper.instance.service.SessionId=ZUtility.ClientXml.GetXmlElementContent("SessionID",res);ISW.ApiWrapper.instance.service.SessionToken=ZUtility.ClientXml.GetXmlElementContent("SessionToken",res);ISW.ApiWrapper.instance.service.SessionId.indexOf("<Error")>=0&&(ISW.ApiWrapper.instance.service.SessionId="",ISW.ApiWrapper.instance.service.SessionToken="");ISW.ApiWrapper.instance.service._handleSessionEstablished();ISW.ApiWrapper.instance.service._initialize()}catch(ex){ISS.log("Error: Unable to retrieve session from server.  "+ex.description);ISW.ApiWrapper.instance.service._handleFailure()}},function(jqXHR,textStatus,ex){ISS.log("an ajax error occured when getting session from server: "+ex.description);ISS.log("Error: "+textStatus+","+ex+","+jqXHR.responseText);ISW.ApiWrapper.instance.service._handleFailure()})},ISS.prototype.getShippingTotal=function(){var rVal=0,sm=ISW.ShippingMethod.GetLoadedById(this.CheckoutPackage.ShippingMethodId);return sm!=null&&(rVal=sm.Price),rVal},ISS.prototype.getOrderTotal=function(){var rVal=-1;return!0&&(rVal=this.Cart.TotalDue),rVal},ISS.prototype.loadApi2MethodsFromServer=function(){ISS.log("Getting API 2 methods from server...");var myUrl=null;myUrl=this.Api2BaseUrl+"GetApi2Methods";ISS.log("Getting store data from server.");this._ajaxS(myUrl,function(res){var o=JSON.parse(res).Data;o==null?ISS.log("Parsed Api2Methods is null"):(ISS.log("Publishing Api2MethodsLoaded"),ISW.Messaging.instance.publish("Api2MethodsLoaded",o))},function(){ISW.ApiWrapper.instance.service._handleFailure()})},ISS.prototype.loadApi2ViewModelsFromServer=function(){ISS.log("Getting API 2 View Models from server...");var myUrl=null;myUrl=this.Api2BaseUrl+"GetApi2ViewModels";ISS.log("Getting store data from server.");this._ajaxS(myUrl,function(res){var o=JSON.parse(res).Data;o==null?ISS.log("Parsed GetApi2ViewModels is null"):(ISS.log("Publishing Api2ViewModelsLoaded"),ISW.Messaging.instance.publish("Api2ViewModelsLoaded",o))},function(){ISW.ApiWrapper.instance.service._handleFailure()})},ISS.prototype.loadStoreDataFromServer=function(){ISS.log("Getting order from server...");var myUrl=null;myUrl=this.Api2BaseUrl+"GetStoreData";ISS.log("Getting store data from server.");this._ajaxS(myUrl,function(res){ISS.log("Get store data response received: "+res);var o=JSON.parse(res).Data;o==null?ISS.log("Parsed StoreData is null"):(ISS.log("Publishing StoreDataLoaded"),ISW.ApiWrapper.instance.service.StoreId<0&&(ISW.ApiWrapper.instance.service.StoreId=o.StoreId),ISW.Messaging.instance.publish("StoreDataLoaded",o))},function(){ISW.ApiWrapper.instance.service._handleFailure()})},ISS.prototype.loadOrderFromServer=function(orderid,orderemail){ISS.log("Getting order from server...");var myUrl=null;this.SessionId==null||this.SessionId==""?(ISS.log("Unable to get order.  Session ID not set."),ISW.ApiWrapper.instance.service._handleFailure()):(myUrl=this.Api2BaseUrl+"GetOrder?OrderID="+orderid+"&OrderEmail="+orderemail.replace("@","%40"),ISS.log("Getting order from server.  OrderId: "+orderid+"; Email: "+orderemail),this._ajaxS(myUrl,function(res){ISS.log("Get Order Response Received: "+res);var o=Order.parseFromJsonObject(JSON.parse(res).Data);o==null?ISS.log("Parsed order is null"):(ISS.log("Loading shipping and billing info from cookie."),o.BillingAddress=ISS.getObjectCookie("IswAddress_Billing_"+ISW.Util.getStoreUri()),o.ShippingAddress=ISS.getObjectCookie("IswAddress_Shipping_"+ISW.Util.getStoreUri()),o.PaymentMethod=ISS.getObjectCookie("IswAddressPaymentMethod_"+ISW.Util.getStoreUri()),o.GiftMessage=ISS.getObjectCookie("IswAddressGiftMessage_"+ISW.Util.getStoreUri()),ISW.ApiWrapper.instance.service.ShippingMethods=[],ISW.ApiWrapper.instance.service.ShippingMethods[0]=ISS.getObjectCookie("IswAddress_ShippingMethod_"+ISW.Util.getStoreUri()),ISS.log("Publishing OrderLoaded"),ISW.Messaging.instance.publish("OrderLoaded",o))},function(){ISW.ApiWrapper.instance.service._handleFailure()}))},ISS.prototype._loadCartFromServer=function(success){var myCrid,myUrl;ISS.log("Getting Cart from server...");myUrl=null;this.SessionId==null||this.SessionId==""||this.SessionId.indexOf("<Error")>=0?(ISS.log("Unable to get cart.  Session ID not set.  SessionId: "+this.SessionId+"; SessionToken: "+this.SessionToken),this.SessionId="",this.SessionToken=""):(myCrid="",this.CartRequestId=myCrid,myUrl=this.Api2BaseUrl+"GetCart?StoreID="+this.StoreId+"&SessionID="+this.SessionId+"&CartRequestId="+myCrid,ISS.log("Getting cart from server.  SessionId: "+this.SessionId),this._ajaxS(myUrl,function(res){var newCart=ShoppingCart.parseFromJsonObject(JSON.parse(res).Data);newCart!=null&&newCart.Items!=null&&newCart.CartRequestId==ISW.ApiWrapper.instance.service.CartRequestId?(ApiWrapper.instance.service.Cart=newCart,ISS.log("Cart loaded from server.  JSON object received."),ISW.Messaging.instance.publish("CartUpdated",newCart),success!=null&&success()):newCart==null||newCart.Items==null?ISS.log("Cart received from server, but null data was detected.  Skipping."):newCart.CartRequestId!=ISW.ApiWrapper.instance.service.CartRequestId&&ISS.log("Cart received from server, but CRID provided ("+newCart.CartRequestId+") does not match current ("+ISW.ApiWrapper.instance.service.CartRequestId+").  Skipping.")},function(){ISW.ApiWrapper.instance.service._handleFailure()}))},ISS.prototype._getCartTotalsFromServer=function(success,cartServerActionToPublish){var myCrid,myUrl;cartServerActionToPublish===void 0&&(cartServerActionToPublish="");ISS.log("Getting Cart from server...");myUrl=null;this.SessionId==null||this.SessionId==""||this.SessionId.indexOf("<Error")>=0?(ISS.log("Unable to get cart.  Session ID not set.  SessionId: "+this.SessionId+"; SessionToken: "+this.SessionToken),this.SessionId="",this.SessionToken=""):(myCrid="",this.CartRequestId=myCrid,myUrl=this.Api2BaseUrl+"GetCart?StoreID="+this.StoreId+"&SessionID="+this.SessionId+"&CartRequestId="+myCrid,ISS.log("Getting cart totals from server.  SessionId: "+this.SessionId),this._ajaxS(myUrl,function(res){var newCart=ShoppingCart.parseFromJsonObject(JSON.parse(res).Data);newCart!=null&&newCart.Items!=null&&newCart.CartRequestId==ISW.ApiWrapper.instance.service.CartRequestId?(ApiWrapper.instance.service.Cart.TotalDue=newCart.TotalDue,ApiWrapper.instance.service.Cart.Discount=newCart.Discount,ApiWrapper.instance.service.Cart.GiftCertificates=newCart.GiftCertificates,ApiWrapper.instance.service.Cart.DiscountTotal=newCart.DiscountTotal,ApiWrapper.instance.service.Cart.TaxAmount=newCart.TaxAmount,ApiWrapper.instance.service.Cart.CanCheckout=newCart.CanCheckout,ApiWrapper.instance.service.Cart.ValidationMessage=newCart.ValidationMessage,ISS.log("Cart totals loaded from server.  JSON object received"),cartServerActionToPublish.length>0?ISW.Messaging.instance.publish("CartServerActionCompleted",{Action:cartServerActionToPublish}):ISW.Messaging.instance.publish("CartUpdated",newCart),success!=null&&success()):newCart==null||newCart.Items==null?ISS.log("Cart received from server, but null data was detected.  Skipping."):newCart.CartRequestId!=ISW.ApiWrapper.instance.service.CartRequestId&&ISS.log("Cart received from server, but CRID provided ("+newCart.CartRequestId+") does not match current ("+ISW.ApiWrapper.instance.service.CartRequestId+").  Skipping.")},function(){ISW.ApiWrapper.instance.service._handleFailure()}))},ISS.prototype._getProductFromCacheById=function(idProduct){for(var rVal=null,i=0;i<this.ProductCache.length;i++)if(this.ProductCache[i].ID==idProduct){rVal=this.ProductCache[i];break}return rVal},ISS.prototype._getProductCategoryFromCacheById=function(id){var rVal=null,i;if(this.ProductCategoryCache!=null){for(i=0;i<this.ProductCategoryCache.length;i++)if(this.ProductCategoryCache[i].ID==id){rVal=this.ProductCategoryCache[i];break}}else this.ProductCategoryCache=[];return rVal},ISS.prototype._getProductCategoryFromCacheByName=function(name){var rVal=null,i;if(this.ProductCategoryCache!=null){for(i=0;i<this.ProductCategoryCache.length;i++)if(this.ProductCategoryCache[i].Name==name){rVal=this.ProductCategoryCache[i];break}}else this.ProductCategoryCache=[];return rVal},ISS.prototype.getProductCategoryByName=function(name,useCache,success,error){useCache===void 0&&(useCache=!0);var myUrl=null,o=null;useCache&&(o=this._getProductCategoryFromCacheByName(name));o!=null?(ISS.log("Get product category returned from cache.  ID: "+o.ID),ISW.Messaging.instance.publish("ProductCategoryLoaded",o)):this.SessionId==null||this.SessionId==""?(ISS.log("Unable to get product details.  Session ID not set."),ISW.ApiWrapper.instance.service._handleFailure()):(myUrl=this.ApiBaseUrl+"GetProductList/"+this.StoreId+"/"+name+"/0/true",this._ajaxS(myUrl,function(res){var o=ISW.ProductCategory.ParseFromXml(res);useCache&&ISW.ApiWrapper.instance.service._addToProductCategoryCache(o);ISW.Messaging.instance.publish("ProductCategoryLoaded",o);success!=null&&success(o)},function(){error!=null?error():ISW.ApiWrapper.instance.service._handleFailure()}))},ISS.prototype.loadShippingMethods=function(useCache){if(useCache===void 0&&(useCache=!0),ISS.log("Getting shipping methods..."),this.ShippingMethods!=null&&this.ShippingMethods.length>0&&useCache)ISS.log("Shipping methods already in cache."),ISW.Messaging.instance.publish("ShippingMethodsLoaded",this.ShippingMethods);else if(this.SessionId==null||this.SessionId.length<1)ISS.log("Unable to get shipping methods.  Session ID not present.");else if(this.Cart==null||this.Cart.Items.length==0)ISS.log("Unable to get shipping methods.  Cart is null, has no items, or has not yet been loaded.");else{ISS.log("Retrieving shipping methods from server.");var myUrl=this.ApiBaseUrl+"GetCartShippingMethods/"+this.StoreId+"/"+this.SessionId;this._ajaxS(myUrl,function(res){ISS.log("Get shipping methods response received: "+res);res.indexOf("<Error>")==0?(ISS.log("Initialing blank shipping methods list"),ISW.ApiWrapper.instance.service.ShippingMethods=[]):(ISS.log("Parsing shipping methods list"),ISW.ApiWrapper.instance.service.ShippingMethods=ShippingMethod.ParseListFromXml(res));ISW.ApiWrapper.instance.service.CheckoutPackage.ShippingMethodId<0&&ISW.ApiWrapper.instance.service.ShippingMethods.length>0&&(ISW.ApiWrapper.instance.service.CheckoutPackage.ShippingMethodId=ISW.ApiWrapper.instance.service.ShippingMethods[0].ID);ISW.ApiWrapper.instance.service.saveToLocalStorage("ShippingMethods");ISS.log("Publishing ShippingMethodsLoaded");ISW.Messaging.instance.publish("ShippingMethodsLoaded",ISW.ApiWrapper.instance.service.ShippingMethods)},function(){ISW.ApiWrapper.instance.service._handleFailure()},"designer=1")}},ISS.prototype.loadStateList=function(shipping){var sbText,sList,myUrl;shipping===void 0&&(shipping=!1);sbText=shipping?"Shipping":"Billing";sList=shipping?this.ShippingStateList:this.BillingStateList;ISS.log("get state list: "+sbText);sList.length>0?ISW.Messaging.instance.publish(sbText+"StateListLoaded",sList):this.SessionId!=null&&this.SessionId!=""&&(ISS.log("Contacting server for "+sbText+" state list."),myUrl=this.Api2BaseUrl+"GetStates?ShippingBilling="+sbText+"&Format=JSON&SessionID="+this.SessionId+"&StoreID="+this.StoreId,this._ajaxS(myUrl,function(res){ISS.log(sbText+" State List retrieved from server.");var r=JSON.parse(res);r.OK&&(shipping?ISW.ApiWrapper.instance.service.ShippingStateList=r.Data:ISW.ApiWrapper.instance.service.BillingStateList=r.Data,ISS.log(sbText+" State list parsed."),ISW.ApiWrapper.instance.service.saveToLocalStorage(sbText+"StateList"),ISW.Messaging.instance.publish(sbText+"StateListLoaded",r.Data))},function(){ISW.ApiWrapper.instance.service._handleFailure()}))},ISS.prototype.getStarterCheckoutUrl=function(){var sslDomain=ZUtility.Page.StoreData("SSL_Domain").toLowerCase(),locString=document.location.toString().toLowerCase(),sslDomainMatches=sslDomain.length>0&&locString.indexOf(sslDomain)>0,isInkSoftDomain=locString.indexOf("inksoft.com")>0,c=this.Cart,tString="https://",indexOfFirstSlash,defaultTab;return tString+=!sslDomainMatches&&!isInkSoftDomain&&tString.indexOf("localhost")<0?this.StoreDNSName+"/":document.location.host+"/",indexOfFirstSlash=tString.indexOf("/",10),tString=tString.substring(0,indexOfFirstSlash+1)+this.StoreUri,defaultTab=null,c.containsCustomPersonalization()?defaultTab="productoptions":c.teamNameNumbersEnabled()&&(defaultTab="names-and-numbers"),tString+(defaultTab!=null?"/Cart/"+this.SessionToken+"?defaultTab="+defaultTab:"/Checkout/"+this.SessionToken+"/CheckoutAddress")},ISS.prototype.getCheckoutUrl=function(){var locString=document.location.toString().toLowerCase(),sslDomain=ZUtility.Page.StoreData("SSL_Domain").toLowerCase(),storeUri=ZUtility.Page.StoreData("StoreUri"),sslDomainMatches=sslDomain.length>0&&locString.indexOf(sslDomain)>0,isInkSoftDomain=locString.indexOf("inksoft.com")>0,newLoc=document.location.toString().replace("http://","https://"),baseUrl;return!sslDomainMatches&&!isInkSoftDomain&&newLoc.indexOf("localhost")<0?(baseUrl=this.StoreDNSName+"/",newLoc="https://"+baseUrl+storeUri+"?SessionId="+ISW.ApiWrapper.instance.service.SessionId+"&SessionToken="+ISW.ApiWrapper.instance.service.SessionToken+"&"):newLoc="https://"+document.location.host+"/"+storeUri+"?",newLoc+"Page=Checkout&Secure=1"},ISS.prototype.loadCountryList=function(shipping){var sbText,cList,myUrl;shipping===void 0&&(shipping=!1);sbText=shipping?"Shipping":"Billing";cList=[];ISS.log("get country list: "+sbText);cList=shipping?this.BillingCountryList:this.ShippingCountryList;cList.length>0?ISW.Messaging.instance.publish(sbText+"CountryListLoaded",cList):this.SessionId!=null&&this.SessionId!=""&&(ISS.log("Contacting server for "+sbText+" country list."),myUrl=this.Api2BaseUrl+"GetCountries?ShippingBilling="+sbText+"&SessionID="+this.SessionId+"&StoreID="+this.StoreId,this._ajaxS(myUrl,function(res){ISS.log(sbText+" Country List retrieved from server.");var r=JSON.parse(res);r.OK?(shipping?ISW.ApiWrapper.instance.service.ShippingCountryList=r.Data:ISW.ApiWrapper.instance.service.BillingCountryList=r.Data,ISW.ApiWrapper.instance.service.saveToLocalStorage(sbText+"CountryList"),ISW.Messaging.instance.publish(sbText+"CountryListLoaded",r.Data)):ISS.log("No "+sbText+" Country list available from server.  Result: "+res)},function(){ISW.ApiWrapper.instance.service._handleFailure()}))},ISS.prototype.getProductDetails=function(idProduct,useCache,success,error){var myUrl=null,o=null;useCache&&(o=this._getProductFromCacheById(idProduct));o!=null?(ISS.log("Get product returned from cache.  ID: "+o.ID),ISW.Messaging.instance.publish("ProductLoaded",o)):this.SessionId==null||this.SessionId==""?(ISS.log("Unable to get product details.  Session ID not set."),ISW.ApiWrapper.instance.service._handleFailure()):(myUrl=this.ApiBaseUrl+"GetProduct/"+this.StoreId+"/"+idProduct,this._ajaxS(myUrl,function(res){var o,tItem,newItem,i;if(res!="<ProductResult><\/ProductResult>"){if(o=ISW.Product.ParseFromXml(res),ISW.ApiWrapper.instance.service.Cart!=null)for(i=0;i<ISW.ApiWrapper.instance.service.Cart.Items.length;i++)ISW.ApiWrapper.instance.service.Cart.Items[i].Product.ID==o.ID&&(tItem=ISW.ApiWrapper.instance.service.Cart.Items[i],newItem=new ISW.ShoppingCartItem(o,tItem.Quantity,tItem.ProductStyleId,tItem.ProductStyleSizeId,tItem.CartRetailItemId,tItem.CartRetailItemSizeId,tItem.PersonalizationValues),ISW.ApiWrapper.instance.service.Cart.Items[i]=newItem);useCache&&ISW.ApiWrapper.instance.service._addToProductCache(o,!0);ISW.Messaging.instance.publish("ProductLoaded",o);ISW.ApiWrapper.instance.service._initSizeCharts();success!=null&&success(o)}},function(){error!=null?error():ISW.ApiWrapper.instance.service._handleFailure()}))},ISS.prototype.saveCartItemsToServer=function(){var myCrid,i,cItem,encodedCartJSON;if(this.SessionId==null||this.SessionId=="")ISS.log("Unable to get product details.  Session ID not set."),ISW.ApiWrapper.instance.service._handleFailure();else if(this.CartIsSaving)this.SaveCartOnSaveReturn=!0,ISS.log("A request was made to save JSON cart to server, but the cart is currently saving.  Will save again when current save operation returns.");else{this.CartIsSaving=!0;ISS.log("Saving JSON cart to server.");myCrid=String(Math.random()).substring(2);this.CartRequestId=myCrid;var saveCartUrl=this.Api2BaseUrl+"SetCart?StoreID="+this.StoreId+"&SessionID="+this.SessionId,c=ISW.ApiWrapper.instance.service.Cart,cartCopy=new ShoppingCart;for(cartCopy.CartRequestId=myCrid,cartCopy.DefaultCountryId=c.DefaultCountryId,cartCopy.Discount=c.Discount,cartCopy.GiftCertificates=c.GiftCertificates,cartCopy.DiscountTotal=c.DiscountTotal,cartCopy.ID=c.ID,cartCopy.TaxAmount=c.TaxAmount,cartCopy.TotalDue=c.TotalDue,cartCopy.Items=[],i=0;i<c.Items.length;i++)cItem=c.Items[i],cartCopy.Items[i]=ShoppingCartItem.parseFromJsonObject(cItem),cartCopy.Items[i].Product=null;encodedCartJSON=encodeURIComponent(JSON.stringify(cartCopy));ISS.log("Sending Cart JSON to server: "+JSON.stringify(cartCopy));this._ajaxS(saveCartUrl,function(res){var tCart=null;try{tCart=ShoppingCart.parseFromJsonObject(JSON.parse(res).Data);ISS.log("JSON cart successfully saved to server.  Total Due: "+tCart.TotalDue+". DiscountAmount: "+tCart.DiscountTotal+". Tax Amount: "+tCart.TaxAmount);ISW.ApiWrapper.instance.service.CartSaveRetryCount=0;ISW.ApiWrapper.instance.service.CartIsSaving=!1;ISW.ApiWrapper.instance.service.GetServerTotalsOnSaveCartReturn?ISW.ApiWrapper.instance.service._getCartTotalsFromServer(null,"CartSaved"):ISW.Messaging.instance.publish("CartServerActionCompleted","CartSaved");ISW.ApiWrapper.instance.service.SaveCartOnSaveReturn&&(ISW.ApiWrapper.instance.service.SaveCartOnSaveReturn=!1,ISW.ApiWrapper.instance.service.saveCartItemsToServer())}catch(ex){ISW.ApiWrapper.instance.service.SaveCartTimer!=null&&(window.clearTimeout(ISW.ApiWrapper.instance.service.SaveCartTimer),ISW.ApiWrapper.instance.service.SaveCartTimer=null);ISW.ApiWrapper.instance.service.CartIsSaving=!1;ISW.ApiWrapper.instance.service.SaveCartOnSaveReturn=!1;ISW.ApiWrapper.instance.service.CartSaveRetryCount<ISW.ApiWrapper.instance.service.CartSaveRetryLimit?(ISW.ApiWrapper.instance.service.CartSaveRetryCount++,ISW.ApiWrapper.instance.service.SaveCartTimer=setTimeout(function(){ISW.ApiWrapper.instance.service.saveCartItemsToServer()},2e3)):ISW.ApiWrapper.instance.service.CartSaveRetryCount=0}},function(){ISW.ApiWrapper.instance.service.SaveCartTimer!=null&&(window.clearTimeout(ISW.ApiWrapper.instance.service.SaveCartTimer),ISW.ApiWrapper.instance.service.SaveCartTimer=null);ISW.ApiWrapper.instance.service.CartIsSaving=!1;ISW.ApiWrapper.instance.service.SaveCartOnSaveReturn=!1;ISW.ApiWrapper.instance.service.SaveCartTimer=setTimeout(function(){ISW.ApiWrapper.instance.service.saveCartItemsToServer()},2e3)},"Cart="+encodedCartJSON)}},ISS.prototype.checkoutWithPaypal=function(){if(this.Cart.CanCheckout)this._saveCheckoutPackageCookies(),window.open(this.ApiBaseUrl+this.StoreUri+"/Checkout/PayPalPay/"+this.SessionToken,"_self");else{var errorData={};errorData.Message="Unable to check out.  "+this.Cart.ValidationMessage;ISW.Messaging.instance.publish("CheckoutError",errorData)}},ISS.prototype.isCheckoutValid=function(responseText){var r=JSON.parse(responseText);return r.OK},ISS.prototype.onCheckoutComplete=function(responseText){var r=JSON.parse(responseText);ISW.ApiWrapper.instance.service._saveCheckoutPackageCookies();ISS.log("Checkout completed successfully: "+responseText);ISW.Messaging.instance.publish("CheckoutActionCompleted",{Action:"OrderCreated",Response:r})},ISS.prototype.stopCheckoutAndShowError=function(responseText){var r=JSON.parse(responseText),messageString,i;for(ISW.Messaging.instance.publish("CheckoutError",{Response:r}),messageString="",i=0;i<r.Messages.length;i++)messageString+=r.Messages[i].Content+"; ";alert("Unabled to create order.  "+messageString)},ISS.prototype.createOrder=function(){var myUrl=this.ApiBaseUrl,d={},tcp=this.CheckoutPackage,errorData,myCC,postDataString,key;if(this.SessionId==null||this.SessionId=="")ISS.log("Unable to create order.  Session ID not set.");else if(this.CheckoutPackage.BillingZipMismatch||this.CheckoutPackage.ShippingZipMismatch)alert("The zip code provided is not valid for the selected state.");else if(this.Cart.CanCheckout){myUrl=myUrl.replace("http://","https://");myUrl.indexOf("//")==0&&(myUrl="https:"+myUrl);myUrl+="/"+this.StoreUri+"/Api2/SaveCartOrder";myCC=new CreditCard(tcp.ccNum,tcp.ccExpMonth,tcp.ccExpYear,tcp.ccCVV);d.StoreID=this.StoreId;d.SessionID=this.SessionId;d.SessionToken=this.SessionToken;d.Email=this.CheckoutPackage.Email;d.PaymentMethod=tcp.PaymentMethod;d.AmountDue=this.getOrderTotal();d.CreditCard=JSON.stringify(myCC);d.PurchaseOrderNumber=tcp.PoNum;postDataString="";for(key in d)postDataString+="&"+key+"="+d[key];postDataString=postDataString.replace("&","");ISS.log("Submitting order.  myUrl: "+myUrl+"; postDataString: "+postDataString);this._ajaxS(myUrl,function(res){if(ISW.ApiWrapper.instance.service.isCheckoutValid(res))ISW.ApiWrapper.instance.service.onCheckoutComplete(res);else ISW.ApiWrapper.instance.service.stopCheckoutAndShowError(res)},function(jqXHR,textStatus,ex){ISS.log("Checkout Failed jqXHR: "+ex);ISS.log(jqXHR);ISS.log("Checkout Failed textStatus: "+textStatus);ISS.log("Checkout Failed ex: "+ex);ISW.ApiWrapper.instance.service.stopCheckoutAndShowError(jqXHR.responseText)},postDataString)}else errorData={},errorData.Message="Unable to check out.  "+this.Cart.ValidationMessage,ISW.Messaging.instance.publish("CheckoutError",errorData)},ISS.prototype._saveCheckoutPackageCookies=function(){for(var cp=ISW.ApiWrapper.instance.service.CheckoutPackage,myShippingMethod=null,smList=ISW.ApiWrapper.instance.service.ShippingMethods,i=0;i<smList.length;i++)smList[i].ID==cp.ShippingMethodId&&(myShippingMethod=smList[i]);ISS.setObjectCookie("IswAddress_Billing_"+ISW.Util.getStoreUri(),cp.BillingAddress);ISS.setObjectCookie("IswAddress_Shipping_"+ISW.Util.getStoreUri(),cp.ShippingAddress);ISS.setObjectCookie("IswAddress_ShippingMethod_"+ISW.Util.getStoreUri(),myShippingMethod);ISS.setObjectCookie("IswAddressPaymentMethod_"+ISW.Util.getStoreUri(),cp.PaymentMethod);ISS.setObjectCookie("IswAddressGiftMessage_"+ISW.Util.getStoreUri(),cp.GiftMessage)},ISS.prototype._initSizeCharts=function(){var mDic,el,tEl,key;ISS.log("initializing size charts");mDic=null;ISS.log("checking for size chart data...");el=$("script[type=size-chart-data]");el.length==1&&el.html().length>0?(mDic=JSON.parse(el.html()),ISS.log("Size chart data found")):ISS.log("Size chart data not found");ISS.log("checking for hidden image container...");$("#SizeChartImageLoader").length>0?(ISS.log("exists."),$("#SizeChartImageLoader").html("")):(ISS.log("does not exist.  creating and appending."),tEl=$('<div id="SizeChartImageLoader" style="display: none;"><\/div>'),ISS.log("element created."),$("body").append(tEl));ISS.log("proceeding for each manufacturer.");for(key in mDic)mDic.hasOwnProperty(key)&&(this._appendSizeChartImageElement(key,mDic[key],!0),ISS.log("Size chart for "+key+": "+mDic[key]));ISS.log("size charts loaded.")},ISS.prototype._appendSizeChartImageElement=function(manufacturer,urlTemplate,overrideExisting){var img=$("<img/>");img.attr("src",urlTemplate.replace("{Manufacturer}",manufacturer.replace(/ /g,""))+"?"+(new Date).getTime());img.attr("data-manufacturer",manufacturer);img.attr("override-existing",overrideExisting?"true":"false");img.on("load",function(){var override,pc,i;for(ISW.ISS.log("size chart loaded: "+$(this).attr("src")),override=$(this).attr("override-existing")=="true",pc=ISW.ApiWrapper.instance.service.ProductCache,i=0;i<pc.length;i++)(pc[i].SizeChartUrl==null||override)&&pc[i].Manufacturer.replace("&amp;","and")==$(this).attr("data-manufacturer").replace("&amp;","and")&&(ISW.ISS.log("Doing size chart update"),pc[i].SizeChartUrl=$(this).attr("src"),$('a[data-manufacturer="'+pc[i].Manufacturer+'"]').attr("href",$(this).attr("src")),$('a[data-manufacturer="'+pc[i].Manufacturer+'"]').show())});$("#SizeChartImageLoader").append(img)},ISS.prototype.saveCouponCode=function(){},ISS.prototype.savePoNumber=function(ponum,success,error){ponum===void 0&&(ponum=null);var myUrl=this.ApiBaseUrl,d="",tcp=this.CheckoutPackage;ponum!=null?(this.CheckoutPackage.PoNum=ponum,this.saveToLocalStorage("CheckoutPackage")):ponum=tcp.PoNum;this.SessionId==null||this.SessionId==""?ISS.log("Unable to submit PO number.  Session ID not set."):(myUrl=myUrl.replace("http://","https://"),myUrl+=this.StoreUri+"/SetPurchaseOrderNumber/"+this.StoreId+"/"+this.SessionId,d="PO="+this.CheckoutPackage.PoNum,this._ajaxS(myUrl,function(res){ISS.log("PO number Saved Successfully: "+res);ISW.Messaging.instance.publish("CheckoutActionCompleted",{Action:"EmailSaved"});success!=null&&success(res)},function(){error!=null&&error();ISS.log("Save PO number Failed")},d))},ISS.prototype.saveEmailAddress=function(email,success,error){email===void 0&&(email=null);var myUrl=this.ApiBaseUrl,d="",tcp=this.CheckoutPackage;email!=null&&(this.CheckoutPackage.Email=email);this.SessionId==null||this.SessionId==""?ISS.log("Unable to submit email.  Session ID not set."):(myUrl=myUrl.replace("http://","https://"),myUrl+="SaveCartEmail/"+this.StoreId+"/"+this.SessionId,d="email="+this.CheckoutPackage.Email,this._ajaxS(myUrl,function(res){ISS.log("Email Saved Successfully: "+res);ISW.Messaging.instance.publish("CheckoutActionCompleted",{Action:"EmailSaved"});success!=null&&success(res)},function(){error!=null&&error();ISS.log("Save email Failed")},d))},ISS.prototype.saveShippingMethod=function(id,success,error){id===void 0&&(id=null);var myUrl=this.ApiBaseUrl,d="";id!=null&&(this.CheckoutPackage.ShippingMethodId=id);this.SessionId==null||this.SessionId==""?(ISS.log("Unable to save shipping method.  Session ID not set."),ISW.ApiWrapper.instance.service._handleFailure()):(ISS.log("Saving shipping method to server."),myUrl+="SaveCartShippingMethod/"+this.StoreId+"/"+this.SessionId,d+="method_id="+this.CheckoutPackage.ShippingMethodId,this._ajaxS(myUrl,function(res){ISS.log("Shipping method saved: "+res);ISW.Messaging.instance.publish("CheckoutActionCompleted",{Action:"ShippingMethodSaved"});success!=null&&success(res);ISW.ApiWrapper.instance.service.GetServerTotalsOnSaveCartReturn&&ISW.ApiWrapper.instance.service._getCartTotalsFromServer(null,"CartSaved")},function(){error!=null?error():ISW.ApiWrapper.instance.service._handleFailure()},d))},ISS.prototype.saveGiftMessage=function(){var myUrl=this.ApiBaseUrl,d="designer=1&GiftMessage="+ZUtility.Format.FormatRtSafe(this.CheckoutPackage.GiftMessage);this.SessionId==null||this.SessionId==""?ISS.log("Unable to save gift message.  Session ID not set."):(myUrl=this.ApiBaseUrl+"SaveCartGiftMessage/"+this.StoreId+"/"+this.SessionId,this._ajaxS(myUrl,function(res){ISS.log("Save gift message response received: "+res);ISW.Messaging.instance.publish("CheckoutActionCompleted",{Action:"GiftMessageSaved"})},function(){},d))},ISS.prototype.saveAddress=function(isBilling,a,getCartOnReturn){var myUrl,d,myAddress;getCartOnReturn===void 0&&(getCartOnReturn=!1);myUrl=this.ApiBaseUrl;d="";a!=null&&(isBilling?this.CheckoutPackage.BillingAddress=a:this.CheckoutPackage.ShippingAddress=a);myAddress=isBilling?this.CheckoutPackage.BillingAddress:this.CheckoutPackage.ShippingAddress;this.SessionId==null||this.SessionId==""||myAddress==null?(ISS.log("Unable to get product details.  Session ID not set."),ISW.ApiWrapper.instance.service._handleFailure()):(myUrl=this.ApiBaseUrl+"SaveCart"+(isBilling?"Billing":"Shipping")+"Address/"+this.StoreId+"/"+this.SessionId,d+="street1="+myAddress.Street1,d+="&street2="+myAddress.Street2,d+="&pobox="+myAddress.IsPoBox,d+="&postcode="+myAddress.Zip,d+="&country%5Fid="+myAddress.CountryId,d+="&state%5Fid="+myAddress.StateId,d+="&business="+myAddress.IsBusiness,d+="&address%5Fid="+myAddress.ID,d+="&first%5Fname="+myAddress.FirstName,d+="&last%5Fname="+myAddress.LastName,d+="&phone="+myAddress.Phone,d+="&city="+myAddress.City,isBilling?this._ajaxS(myUrl,function(res){if(ISS.log("Save billing address response received: "+res),res.indexOf("<Error")==0){var data={};data.Message=String(res).replace("<Error>","").replace("<\/Error>","");res.indexOf("phone number")?(data.Action="InvalidPhone",ISW.ApiWrapper.instance.service.CheckoutPackage.BillingZipMismatch=!1,ISW.Messaging.instance.publish("CheckoutError",data)):(data.Action="BillingZipMismatch",ISW.Messaging.instance.publish("CheckoutError",data),ISW.ApiWrapper.instance.service.CheckoutPackage.BillingZipMismatch=!0)}else ISW.ApiWrapper.instance.service.CheckoutPackage.BillingZipMismatch=!1,ISW.Messaging.instance.publish("CheckoutActionCompleted",{Action:"BillingAddressSaved"}),ISW.ApiWrapper.instance.service._getCartTotalsFromServer(null,"CartSaved")},function(){ISW.ApiWrapper.instance.service._handleFailure()},d):this._ajaxS(myUrl,function(res){if(ISS.log("Save shipping address response received: "+res),res.indexOf("<Error")==0){var data={};data.Message=String(res).replace("<Error>","").replace("<\/Error>","");res.indexOf("phone number")?(data.Action="InvalidPhone",ISW.ApiWrapper.instance.service.CheckoutPackage.ShippingZipMismatch=!1,ISW.Messaging.instance.publish("CheckoutError",data)):(data.Action="ShippingZipMismatch",ISW.Messaging.instance.publish("CheckoutError",data),ISW.ApiWrapper.instance.service.CheckoutPackage.ShippingZipMismatch=!0)}else ISW.ApiWrapper.instance.service.CheckoutPackage.ShippingZipMismatch=!1,ISW.Messaging.instance.publish("CheckoutActionCompleted",{Action:"ShippingAddressSaved"}),ISW.ApiWrapper.instance.service.loadShippingMethods(!1)},function(){ISW.ApiWrapper.instance.service._handleFailure()},d))},ISS.prototype._ajaxS=function(url,success,error,data,verb){data==null&&(data="");verb==null&&(verb=data==""?"GET":"POST");$.ajax({type:verb,url:url,dataType:"text",data:data,processData:!1,crossDomain:!0,success:function(res){success(res)},error:function(jqXHR,textStatus,ex){error(jqXHR,textStatus,ex)}})},ISS.LogOutput=document.location.toString().indexOf("localhost")>0||document.location.toString().indexOf("ShowLog=true")>0,ISS}();ISW.ISS=ISS,function(ApiStatus){ApiStatus[ApiStatus.Unloaded=0]="Unloaded";ApiStatus[ApiStatus.Downloading=1]="Downloading";ApiStatus[ApiStatus.Ready=2]="Ready"}(ApiStatus||(ApiStatus={}));ApiWrapper=function(){function ApiWrapper(){}return ApiWrapper.loadScript=function(){ApiWrapper.status==ApiStatus.Unloaded&&(ApiWrapper.status=ApiStatus.Downloading,ApiWrapper.instance.service=new ISS,ApiWrapper.instance.service._initialize())},ApiWrapper.onLoadComplete=function(){ApiWrapper.status=ApiStatus.Ready;ApiWrapper.notifyWhenReady(null)},ApiWrapper.notifyWhenReady=function(widgetInstance){function notify(instance){if(typeof instance.apiReady=="function")try{instance.apiReady()}catch(ex){ISW.Util.logWidgetError("Error running apiReady()",instance.className,ex)}}if(ApiWrapper.status!=ApiStatus.Ready)widgetInstance&&ApiWrapper.waiting.push(widgetInstance),ApiWrapper.loadScript();else{for(var i=0;i<ApiWrapper.waiting.length;i++)notify(ApiWrapper.waiting[i]);ApiWrapper.waiting=[];widgetInstance&&notify(widgetInstance)}},ApiWrapper.instance=new ApiWrapper,ApiWrapper.status=ApiStatus.Unloaded,ApiWrapper.waiting=[],ApiWrapper}();ISW.ApiWrapper=ApiWrapper})(ISW||(ISW={})),function(ISW){var Util=function(){function Util(){}return Util.logWidgetError=function(msg,widgetName,ex){return console&&console.error({msg:msg,widget:widgetName,exception:ex}),!1},Util.getUTCNow=function(){var d=new Date;return new Date(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),d.getUTCMilliseconds())},Util.fixDigits=function(inNum,places){for(var rVal=""+inNum;rVal.length<places;)rVal="0"+rVal;return rVal},Util.rgb2hex=function(rgb){function hex(x){return("0"+parseInt(x).toString(16)).slice(-2)}return rgb=rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/),hex(rgb[1])+hex(rgb[2])+hex(rgb[3])},Util.getContrastHexColor=function(hexColor){var prependPound=hexColor.indexOf("#")==0,color=hexColor.replace("#","");color.length==3&&(color=""+color[0]+color[0]+color[1]+color[1]+color[2]+color[2]);try{color=parseInt(color,16)>8947848?"000000":"FFFFFF";prependPound&&(color="#"+color)}catch(ex){ISW.ISS.log("getContrastHexColor error: "+ex.description)}return color},Util.getInverseHexColor=function(hexColor){var prependPound=hexColor.indexOf("#")==0,color=hexColor.replace("#","");try{color.length==3&&(color=""+color[0]+color[0]+color[1]+color[1]+color[2]+color[2]);color=parseInt(color,16);color=16777215^color;color=color.toString(16);color=("000000"+color).slice(-6);prependPound&&(color="#"+color)}catch(ex){ISW.ISS.log("getInverseHexColor error: "+ex.description)}return color},Util.getStoreUri=function(){var rVal=document.location.toString(),tIndex,success=!1;if($("StoreData").length>0)try{rVal=$("StoreData").attr("StoreUri");success=!0;ISW.ISS.log("Uri retrieved from HTML: "+rVal)}catch(ex){ISW.ISS.log("Uri not parsed from HTML.  An error occurred.")}else ZUtility.Page.RequestVal("StoreUri").length>0?(rVal=ZUtility.Page.RequestVal("StoreUri"),success=!0,ISW.ISS.log("StoreUri is blank in HTML. Taking from query string: "+rVal)):ISW.ISS.log("StoreUri is blank in HTML.");return success||(tIndex=rVal.indexOf("?"),tIndex>0&&(rVal=rVal.substring(0,tIndex)),rVal.indexOf("/",10)<0||rVal.indexOf("/",10)+1==rVal.length?rVal=document.location.host.split(".")[0]:(tIndex=rVal.indexOf("/",10),rVal=rVal.substring(tIndex+1),tIndex=rVal.indexOf("/"),tIndex>0&&(rVal=rVal.substring(0,tIndex)),tIndex=rVal.indexOf("#"),tIndex>0&&(rVal=rVal.substring(0,tIndex)))),rVal},Util.MonthNames=["","January","February","March","April","May","June","July","August","September","October","November","December"],Util.MonthNamesShort=["","Jan","Feb","March","April","May","June","July","Aug","Sept","Oct","Nov","Dec"],Util}();ISW.Util=Util}(ISW||(ISW={})),function(ISW){var DependencyManager=function(){function DependencyManager(){}return DependencyManager.getByType=function(className){return DependencyManager.typeDependencies.hasOwnProperty(className)||(DependencyManager.typeDependencies[className]=new WidgetDependencies(className)),DependencyManager.typeDependencies[className]},DependencyManager.checkAllDependencies=function(){var list=[],allInterfaces,type,typeList,unfilled,i,wd,requiresList,j,requirement,item;for(type in DependencyManager.typeDependencies)list.push(DependencyManager.typeDependencies[type]);allInterfaces={};for(type in DependencyManager.typeDependencies)for(typeList=DependencyManager.typeDependencies[type].getInterfaces(),i=0;i<typeList.length;i++)allInterfaces[typeList[i]]=!0;for(unfilled={},i=0;i<list.length;i++)for(wd=list[i],requiresList=wd.getRequirements(),j=0;j<requiresList.length;j++)requirement=requiresList[j],allInterfaces.hasOwnProperty(requirement)||(unfilled.hasOwnProperty(requirement)||(unfilled[requirement]={interface:requirement,neededBy:[]}),unfilled[requirement].neededBy.push(wd.widgetType));for(requirement in unfilled)item=unfilled[requirement],ISW.DependencyManager.loadDefaultImplementation(item.interface,item.neededBy[0])},DependencyManager.loadDefaultImplementation=function(interfaceList,neededBy){$.isArray(interfaceList)||(interfaceList=[interfaceList]);for(var i=0;i<interfaceList.length;i++)ISW.Util.logWidgetError("Unable to load widget dependency - "+interfaceList[i],neededBy)},DependencyManager.typeDependencies={},DependencyManager}(),WidgetDependencies;ISW.DependencyManager=DependencyManager;WidgetDependencies=function(){function WidgetDependencies(className){this.requirements={};this.implementations={};this.widgetType=className}return WidgetDependencies.prototype.implements=function(interfaceList){$.isArray(interfaceList)||(interfaceList=[interfaceList]);for(var i=0;i<interfaceList.length;i++)this.implementations[interfaceList[i]]=!0},WidgetDependencies.prototype.require=function(interfaceList){$.isArray(interfaceList)||(interfaceList=[interfaceList]);for(var i=0;i<interfaceList.length;i++)this.requirements[interfaceList[i]]=!0},WidgetDependencies.prototype.getInterfaces=function(){var ret=[];for(var key in this.implementations)ret.push(key);return ret},WidgetDependencies.prototype.getRequirements=function(){var ret=[];for(var key in this.requirements)ret.push(key);return ret},WidgetDependencies}();ISW.WidgetDependencies=WidgetDependencies}(ISW||(ISW={})),function(ISW){var TypeLoaderConfig=function(){function TypeLoaderConfig(){}return TypeLoaderConfig.baseURL="//"+document.location.host+"/widget",TypeLoaderConfig.widgetBaseURL=TypeLoaderConfig.baseURL+"/widget.ashx?names=",TypeLoaderConfig.loadMultiple=!0,TypeLoaderConfig.urlExtension="",TypeLoaderConfig}(),WidgetType,WidgetTypeLoading,TypeLoader;ISW.TypeLoaderConfig=TypeLoaderConfig;WidgetType=function(){function WidgetType(name){this.name=name}return WidgetType}();ISW.WidgetType=WidgetType;WidgetTypeLoading=function(){function WidgetTypeLoading(name){this.name=name;this.pendingFunctions=[]}return WidgetTypeLoading}();ISW.WidgetTypeLoading=WidgetTypeLoading;TypeLoader=function(){function TypeLoader(){}return TypeLoader.load=function(typeList,callback){var type,urls,filesLeftToLoad,i,url;for($.isArray(typeList)||(typeList=[typeList]),ISW.ISS.log("Loading types: "+typeList.join(",")),i=typeList.length-1;i>=0;i--)type=typeList[i],TypeLoader.types.hasOwnProperty(type)&&typeList.splice(i,1);if(typeList.length==0){typeof callback=="function"&&callback();return}for(i=typeList.length-1;i>=0;i--)type=typeList[i],TypeLoader.typesloading.hasOwnProperty(type)&&(typeList.splice(i,1),TypeLoader.typesloading[type].pendingFunctions[TypeLoader.typesloading[type].pendingFunctions.length]=callback);if(typeList.length>0)for(urls=TypeLoader.getUrl(typeList),filesLeftToLoad=urls.length,i=0;i<urls.length;i++)url=urls[i],TypeLoader.loadWidgetPackage(url,function(){--filesLeftToLoad==0&&typeof callback=="function"&&callback()})},TypeLoader.loadAllForPage=function(callback){var divArray=[],cString="",t,ta,i,j;if(divArray=$("div[widget-type]").toArray(),divArray.length>0)for(t=$(divArray[0]).attr("widget-type"),cString=t,TypeLoader.typesloading.hasOwnProperty(t)||(TypeLoader.typesloading[t]=new WidgetTypeLoading(t)),i=1;i<divArray.length;i++)t=$(divArray[i]).attr("widget-type"),TypeLoader.typesloading.hasOwnProperty(t)||(TypeLoader.typesloading[t]=new WidgetTypeLoading(t),cString+=","+t);if(divArray=$("div[widget-types]").toArray(),divArray.length>0)for(i=0;i<divArray.length;i++)for(t=$(divArray[i]).attr("widget-types"),ta=t.indexOf(",")>0?t.split(","):"",ta.length>0&&(cString+=ta[0]),j=1;j<ta.length;j++)TypeLoader.hasOwnProperty(ta[j])||(TypeLoader.typesloading[ta[j]]=new WidgetTypeLoading(ta[j]),cString+=","+ta[j]);cString.trim().length>0&&TypeLoader.loadWidgetPackage(TypeLoaderConfig.widgetBaseURL+cString,callback)},TypeLoader.loadWidgetPackage=function(url,callback){ISW.ISS.log("url: "+url);$.ajax({url:url,success:function(res){$("body").append(res.replace(/text\/javascript/g,"text/html"));TypeLoader.importScriptBlocks();typeof callback=="function"&&callback()},error:function(xhr,textStatus,errorThrown){textStatus=="timeout"?ISW.Util.logWidgetError("Timeout loading widget url",url,errorThrown):ISW.Util.logWidgetError('Received status "'+textStatus+'" loading widget url',url,errorThrown)}})},TypeLoader.getUrl=function(typeList){var ret=[],i,mytype;if($.isArray(typeList)||(typeList=[typeList]),TypeLoaderConfig.loadMultiple)typeList.length>0&&typeList[0].trim().length>0&&ret.push(TypeLoaderConfig.widgetBaseURL+typeList.join(",")+TypeLoaderConfig.urlExtension);else for(i=0;i<typeList.length;i++)mytype=typeList[i],mytype.trim().length>0&&ret.push(TypeLoaderConfig.widgetBaseURL+mytype+TypeLoaderConfig.urlExtension);return ret},TypeLoader.importScriptBlocks=function(){$("script[widget-type=widget-html]").each(function(){var $this=$(this),name=$this.attr("widget"),html=$this.html();if($this.remove(),!name)return ISW.Util.logWidgetError('Script of widget-type "widget-html" without widget attribute was not processed');TypeLoader.types.hasOwnProperty(name)==!1&&(TypeLoader.types[name]=new WidgetType(name));TypeLoader.types[name].html=html});$("script[widget-type=widget-js]").each(function(){var $this=$(this),name=$this.attr("widget"),js=$this.html(),fn,tl,i;if($this.remove(),!name)return ISW.Util.logWidgetError('Script of widget-type "widget-js" without widget attribute was not processed');fn=null;js="fn = function() { "+js+"}";try{eval(js)}catch(ex){return ISW.Util.logWidgetError("Error parsing constructor",name,ex)}if(TypeLoader.types.hasOwnProperty(name)==!1&&(TypeLoader.types[name]=new WidgetType(name)),TypeLoader.types[name].fn=fn,TypeLoader.typesloading.hasOwnProperty(name)){for(tl=TypeLoader.typesloading[name],i=0;i<tl.pendingFunctions.length;i++)tl.pendingFunctions[i]();delete TypeLoader.typesloading[name]}})},TypeLoader.typesloading={},TypeLoader.types={},TypeLoader}();ISW.TypeLoader=TypeLoader}(ISW||(ISW={})),function(ISW){var Messaging=function(){function Messaging(){this.topics={};this.lastUid=-1}return Messaging.prototype.subscribe=function(topic,func){this.topics.hasOwnProperty(topic)||(this.topics[topic]=[]);var token=(++this.lastUid).toString();return this.topics[topic].push({token:token,func:func}),token},Messaging.prototype.unsubscribe=function(token){var m,i;for(m in this.topics)if(this.topics.hasOwnProperty(m))for(i=0;i<this.topics[m].length;i++)if(this.topics[m][i].token===token)return this.topics[m].splice(i,1),token;return null},Messaging.prototype.publish=function(topic,data){var throwException,subscribers,i;if(!this.topics.hasOwnProperty(topic))return!1;for(throwException=function(e){return function(){throw e;}},subscribers=this.topics[topic],i=0;i<subscribers.length;i++)try{subscribers[i].func(topic,data)}catch(e){setTimeout(throwException(e),0)}},Messaging.prototype.link=function(url,topic,data){var q=encodeURIComponent(topic)+"=";q+=jQuery.type(data)==="string"?encodeURIComponent(data):encodeURIComponent(JSON.stringify(data));url+=url.indexOf("?")>-1?"&"+q:"?"+q;document.location.href=url},Messaging.prototype.triggerQueryStringEvents=function(){var url=""+document.location,qi=url.indexOf("?"),q,parts,i,eq,value,key;if(qi!=-1)for(q=url.substring(qi+1),parts=q.split("&"),i=0;i<parts.length;i++)eq=parts[i].indexOf("="),eq>-1?(key=decodeURIComponent(parts[i].substring(0,eq)),value=decodeURIComponent(parts[i].substring(eq+1)),this.publish(key,value)):(key=decodeURIComponent(parts[i]),this.publish(key,null))},Messaging.instance=new Messaging,Messaging}();ISW.Messaging=Messaging}(ISW||(ISW={})),function(ISW){var WidgetInstance=function(){function WidgetInstance(container,className,options){options===void 0&&(options={});this.className=className;this.type=ISW.TypeLoader.types[className];this.container=$("#"+container);this.api=ISW.ApiWrapper.instance;this.events=ISW.Messaging.instance;this.designer=ISW.Designer.getByType(className);this.dependencies=ISW.DependencyManager.getByType(className);this.log=function(message){ISW.ISS.log(this.className+" | "+message)};this.options=options||{};ISW.Factory.register(this)}return WidgetInstance.prototype.$=function(selector){return this.container.find(selector)},WidgetInstance.prototype.init=function(){},WidgetInstance.prototype.htmlReady=function(){},WidgetInstance.prototype.apiReady=function(){},WidgetInstance.prototype.instantiate=function(){var failure=this.type==null||this.type.fn==null||this.type.html==null||this.init==null;if(failure)ISW.Util.logWidgetError("Error instantiating widget.",this.className,"");else{if(typeof this.type.fn=="function")try{this.type.fn.apply(this)}catch(ex){ISW.Util.logWidgetError("Error running widget constructor",this.className,ex)}if(typeof this.init=="function")try{this.init()}catch(ex){ISW.Util.logWidgetError("Error running init()",this.className,ex)}if(this.type.html&&this.container.html(this.type.html),typeof this.htmlReady=="function")try{this.htmlReady()}catch(ex){ISW.Util.logWidgetError("Error running htmlReady()",this.className,ex)}ISW.ApiWrapper.notifyWhenReady(this)}},WidgetInstance}();ISW.WidgetInstance=WidgetInstance}(ISW||(ISW={})),function(ISW){var Factory=function(){function Factory(){}return Factory.create=function(container,className,options){ISW.TypeLoader.load(className,function(){var w=new ISW.WidgetInstance(container,className,options);w.instantiate()})},Factory.createDefaults=function(){$("[widget-default]").each(function(){var id=$(this).attr("id"),className=$(this).attr("widget-default"),widget=Factory.getByContainer(id);widget==null})},Factory.getByContainer=function(container){var uid,w;for(uid in Factory.activeWidgets)if(w=Factory.activeWidgets[uid],w.container.attr("id")==container)return w;return null},Factory.getByInstanceId=function(uid){return Factory.activeWidgets[uid]},Factory.register=function(w){w.id=++Factory.lastUid;Factory.activeWidgets[w.id]=w},Factory.eachWidget=function(fn){for(var uid in Factory.activeWidgets)fn(parseInt(uid),Factory.activeWidgets[uid])},Factory.activeWidgets={},Factory.lastUid=-1,Factory}();ISW.Factory=Factory}(ISW||(ISW={})),function(ISW){var Designer=function(){function Designer(){}return Designer.getByType=function(className){return Designer.widgetDesigners.hasOwnProperty(className)||(Designer.widgetDesigners[className]=new WidgetDesigner(className)),Designer.widgetDesigners[className]},Designer.showEditMode=function(){var url=ISW.TypeLoaderConfig.widgetBaseURL+"editor.html";$.get(url,function(html){$("body").append(html)})},Designer.widgetDesigners={},Designer.editorCSSLoaded=!1,Designer}(),WidgetDesignerField,WidgetDesigner;ISW.Designer=Designer;WidgetDesignerField=function(){function WidgetDesignerField(){this.editor="text"}return WidgetDesignerField}();ISW.WidgetDesignerField=WidgetDesignerField;WidgetDesigner=function(){function WidgetDesigner(className){this.fields={};this.widgetType=className}return WidgetDesigner.prototype.addField=function(id,options){this.fields[id]=options},WidgetDesigner}();ISW.WidgetDesigner=WidgetDesigner}(ISW||(ISW={})),function(ISW){var Widget=function(){function Widget(){}return Widget.insert=function(container,className,options){ISW.Factory.create(container,className,options)},Widget.embed=function(className,options){var id="isw_"+String(Math.random()).substring(2);document.write('<div id="'+id+'"><\/div>');Widget.insert(id,className,options)},Widget.getWidgetByContainer=function(container){return ISW.Factory.getByContainer(container)},Widget.showEditMode=function(){ISW.Designer.showEditMode()},Widget.autoLoadWidgetsOnPage=function(){for(var divArray=$("div[widget-type]").toArray(),tID,tWT,tWO,i=0;i<divArray.length;i++)tID=$(divArray[i]).attr("id"),tWT=$(divArray[i]).attr("widget-type"),tWO=$(divArray[i]).attr("widget-options")!=null?$(divArray[i]).attr("widget-options").replace(/'/g,'"'):"",tID!=null&&tID.length>0&&tWT!=null&&tWT.length>0&&tWT!="widgetlist"&&(tWO==null||tWO.length<1||tWO.indexOf("{")!=0||tWO.lastIndexOf("}")!=tWO.length-1?ISW.Widget.insert(tID,tWT):ISW.Widget.insert(tID,tWT,JSON.parse(tWO)))},Widget}();ISW.Widget=Widget;$(document).ready(function(){ISW.TypeLoader.loadAllForPage(function(){Widget.autoLoadWidgetsOnPage()});ISW.Factory.createDefaults();ISW.Messaging.instance.triggerQueryStringEvents();ISW.DependencyManager.checkAllDependencies()})}(ISW||(ISW={})),function(ZUtility){var Num=function(){function Num(){}return Num.GetDecimal=function(inNum){return Number(parseInt(""+Math.round(inNum*100))/100)},Num}(),DateAndTime,Cookie,Page,Validation,Debug,Format,StringBuffer,Array,ClientXml,XmlParsedPackage;ZUtility.Num=Num;DateAndTime=function(){function DateAndTime(){}return DateAndTime.GetDstStartDate=function(){var currentDate=new Date,d=new Date(currentDate.getFullYear(),2,1),firstOfMonthDayOfWeek=d.getDay(),daysUntilFirstSunday=(7-firstOfMonthDayOfWeek)%7,secondSundayOfMarch=d.getDate()+daysUntilFirstSunday+7;return new Date(d.getFullYear(),2,secondSundayOfMarch)},DateAndTime.GetDstEndDate=function(){var currentDate=new Date,d=new Date(currentDate.getFullYear(),10,1),firstOfMonthDayOfWeek=d.getDay(),daysUntilFirstSunday=(7-firstOfMonthDayOfWeek)%7,firstSundayOfNovember=d.getDate()+daysUntilFirstSunday;return new Date(d.getFullYear(),10,firstSundayOfNovember)},DateAndTime.GetTimeZoneList=function(){var dstStart=DateAndTime.GetDstStartDate(),dstEnd=DateAndTime.GetDstEndDate(),currentDate=new Date,isDst=dstStart.getTime()<currentDate.getTime()&&currentDate.getTime()<dstEnd.getTime();return isDst?DateAndTime.dstTimeZones:DateAndTime.stdTimeZones},DateAndTime.GetLocalGmtOffset=function(){return(new Date).getTimezoneOffset()/-60},DateAndTime.GetEncodedGmtOffset=function(encodedDate){return(11-encodedDate.getHours())*-1},DateAndTime.GetLocalOffsetDate=function(encodedDate){var dateGmtOffset=ZUtility.DateAndTime.GetEncodedGmtOffset(encodedDate),localGmtOffset=DateAndTime.GetLocalGmtOffset(),offsetDiff=localGmtOffset-dateGmtOffset;return new Date(encodedDate.getFullYear(),encodedDate.getMonth(),encodedDate.getDate(),offsetDiff)},DateAndTime.stdTimeZones=[{Offset:-10,Name:"HST (Hawaii)"},{Offset:-9,Name:"AKST (Alaska)"},{Offset:-8,Name:"PST (California)"},{Offset:-7,Name:"MST (Arizona / Colorado)"},{Offset:-6,Name:"CST (Missouri)"},{Offset:-5,Name:"EST (New York)"},{Offset:-4,Name:"AST (Newfoundland)"}],DateAndTime.dstTimeZones=[{Offset:-10,Name:"HST (Hawaii)"},{Offset:-8,Name:"AKDT (Alaska)"},{Offset:-7,Name:"PDT / MST (California / Arizona)"},{Offset:-6,Name:"MDT (Colorado)"},{Offset:-5,Name:"CDT (Missouri)"},{Offset:-4,Name:"EDT (New York)"},{Offset:-3,Name:"ADT (Newfoundland)"}],DateAndTime}();ZUtility.DateAndTime=DateAndTime;Cookie=function(){function Cookie(){var ca,ct,myArray,i;for(this.Items={},ca=document.cookie.split(";"),ct="",i=0;i<ca.length;i++)ct=ca[i].trim(),myArray=ct.split("="),myArray.length>1&&(this.Items[myArray[0]]=myArray[1])}return Cookie}();ZUtility.Cookie=Cookie;Page=function(){function Page(){}return Page.ExtractTemplates=function(container){var r=[];return container.$(".template-container").each(function(){var tName=$(this).attr("data-name"),s;r.hasOwnProperty(tName)||(s=$(this).html(),r[tName]=s,$(this).remove())}),r},Page.AddCss=function(path){if(document.getElementsByTagName("head")[0].innerHTML.indexOf(path)<0){var s=document.createElement("link");s.setAttribute("rel","stylesheet");s.setAttribute("type","text/css");s.setAttribute("src",path);document.getElementsByTagName("head")[0].appendChild(s)}},Page.AddScript=function(path){if(document.getElementsByTagName("head")[0].innerHTML.indexOf(path)<0){var s=document.createElement("script");s.setAttribute("type","text/javascript");s.setAttribute("src",path);document.getElementsByTagName("head")[0].appendChild(s)}},Page.StoreData=function(itemName){var tVal=$("StoreData").attr(itemName);return(typeof tVal==typeof undefined||tVal===!1)&&(tVal=""),tVal},Page.SessionData=function(itemName){var tVal=$("SessionData").attr(itemName);return(typeof tVal==typeof undefined||tVal===!1)&&(tVal=""),tVal},Page.GetDataObjectFromAttributes=function(attributeSourceJqueryElement){var rVal={};return $(attributeSourceJqueryElement[0].attributes).each(function(){rVal[this.nodeName]=this.nodeValue}),rVal},Page.RequestVal=function(name){name=name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var regexS="[\\?&]"+name+"=([^&#]*)",regex=new RegExp(regexS),results=regex.exec(window.location.href);return results==null?"":decodeURIComponent(results[1].replace(/\+/g," "))},Page.PreloadImages=function(paths){var pe,ti,d,i;if($("#ImagePreloaderDiv").length<1){d=document.createElement("div");d.style.display="none";d.id="ImagePreloaderDiv";try{document.body.appendChild(d)}catch(ex){alert("Error appending preloader div: "+ex)}}for(pe=$("#ImagePreloaderDiv"),i=0;i<paths.length;i++)ti=new Image,ti.src=paths[i],pe.append(ti)},Page}();ZUtility.Page=Page;Validation=function(){function Validation(){}return Validation.IsNumericCharacter=function(char){return this.numericRegex.test(char)},Validation.IsValidPhoneCharacter=function(char){return this.phoneRegex.test(char)},Validation.IsValidEmail=function(val){return this.emailRegex.test(val)},Validation.CleanPhoneField=function(jField){for(var oldString=jField.val(),newString="",tc,ntc,i=0;i<oldString.length;i++)tc=oldString[i],ntc=newString.length>0?newString[newString.length-1]:null,this.IsValidPhoneCharacter(tc)&&(tc!="#"||newString.length>7&&newString.indexOf("#")<0)&&(tc!="+"||newString.length<1)&&(tc!=")"||newString.indexOf("(")>=0&&newString.indexOf(")")<0)&&(tc!="("||newString.indexOf("(")<0)&&(ntc==null||this.IsNumericCharacter(tc)||ntc==")"&&tc==" "||this.IsNumericCharacter(ntc))&&(newString+=oldString[i]);newString.length>0&&newString[0]==" "&&(newString=newString.substring(1));oldString!=newString&&jField.val(newString)},Validation.ValidatePhoneKeyPress=function(jField,evt){var theEvent=evt||window.event,key=theEvent.keyCode||theEvent.which,regex;key=String.fromCharCode(key);regex=/[0-9.-]|\.|\s/;this.IsValidPhoneCharacter(key)||(theEvent.returnValue=!1,theEvent.preventDefault&&theEvent.preventDefault())},Validation.IsNullOrEmpty=function(val){return!val||val.length===0},Validation.IsNullOrWhiteSpace=function(val){return!val||val.trim().length===0},Validation.IsNumeric=function(val){var parsedVal=parseFloat(""+val);return isNaN(parsedVal)||""+parsedVal!=""+val?!1:!0},Validation.IsEmail=function(val){return/\S+@\S+\.\S+/.test(val)},Validation.ParseIntegerId=function(val){var rVal=-1;return Validation.IsNumeric(val)&&(rVal=parseInt(val)),rVal},Validation.IsInteger=function(val){var rVal=!0,parsedVal=parseInt(val);return(isNaN(parsedVal)||""+parsedVal!=""+val)&&(rVal=!1),rVal},Validation.IsDateTime=function(val){var rVal=!0,tDT;try{tDT=Date.parse(val)}catch(ex){rVal=!1}return rVal},Validation.phoneRegex=/[0-9\#\s\(\)+.-]/,Validation.numericRegex=/^\d+$/,Validation.emailRegex=/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/,Validation}();ZUtility.Validation=Validation;Debug=function(){function Debug(){}return Debug.Dump=function(arr,level){var rVal="",level_padding,j,item,value;for(level||(level=0),level_padding="",j=0;j<level+1;j++)level_padding+="    ";if(typeof arr=="object")for(item in arr)value=arr[item],typeof value=="object"?(rVal+=level_padding+"'"+item+"' ...\n",rVal+=Debug.Dump(value,level+1)):rVal+=level_padding+"'"+item+"' => \""+value+'"\n';else rVal="===>"+arr+"<===("+typeof arr+")";return rVal},Debug}();ZUtility.Debug=Debug;Format=function(){function Format(){}return Format.AssignWidgetProperties=function(w){$.each(w.options,function(key){w[key]=w.options[key]})},Format.InsertAttributeValues=function(htmlSourceJqueryElement,attributeSourceJqueryElement){var myHtml=null;if(htmlSourceJqueryElement==null||attributeSourceJqueryElement==null)return"";try{myHtml=htmlSourceJqueryElement.html()}catch(ex){return""}myHtml==null||typeof myHtml=="undefined"?ISW.ISS.log("unable to insert attribute values.  HTML is null."):($(attributeSourceJqueryElement[0].attributes).each(function(){myHtml=myHtml.replace(new RegExp("{{"+this.nodeName+"}}","gi"),this.nodeValue)}),htmlSourceJqueryElement.html(myHtml))},Format.InsertDictionaryValues=function(sourceString,sourceDictionary){var myHtml=sourceString,key;if(sourceString==null||sourceDictionary==null)return sourceString;for(key in sourceDictionary)myHtml=myHtml.replace(new RegExp("{{"+key+"}}","gi"),sourceDictionary[key]);return myHtml},Format.MVCFriendlyEncode=function(input){var output,i;if(!input)return"";for(input=input.replace(/&amp;/g,""),input=input.replace(/\//g,"_"),output="",i=0;i<input.length;i++)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-().".indexOf(input[i])>=0?output+=input[i]:"[{".indexOf(input[i])>=0?output+="(":"]}".indexOf(input[i])>=0?output+=")":input[i]=="&"?output+="And":input[i]==" "&&(output+="_");for(output=output.replace(/__/g,"_").replace(/\.\./g,".");output.indexOf("_")==output.length-1;)output=output.substring(0,output.length-2);while(output.indexOf(".")==output.length-1)output=output.substring(0,output.length-2);while(output.indexOf("_")==0)output=output.substring(1);while(output.indexOf(".")==0)output=output.substring(1);return output},Format.HtmlDecode=function(input){var e=document.createElement("textarea");return e.innerHTML=input,e.value==null?"":e.value},Format.FixDigits=function(num,places){for(var tString=""+num;tString.length<places;)tString="0"+tString;return tString},Format.FormatSimpleLinkString=function(url,text){return'<a href="'+url+'" target="_blank">'+text+"<\/a>"},Format.FormatCurrencyWithCommas=function(inAmount,forceDecimal,prependCurrencySymbol,appendCurrencyCode){var rString,amount,tString,i,t,currencySymbol,currencyCode;if(forceDecimal===void 0&&(forceDecimal=!1),prependCurrencySymbol===void 0&&(prependCurrencySymbol=!0),appendCurrencyCode===void 0&&(appendCurrencyCode=!1),amount=Number(inAmount),!amount||isNaN(amount)||amount==0)rString="0.00";else if(amount)for(amount=Math.round(amount*100),tString=""+amount,tString.indexOf(".")>0&&(tString=tString.split(".")[0]),tString.length<3?(rString="."+tString,tString="0"):(rString="."+tString.substring(tString.length-2),tString=tString.substring(0,tString.length-2)),i=tString.length-1,t=0;i>=0;)t==3?(t=1,rString=","+rString):t++,rString=tString[i]+rString,i--;return forceDecimal||(rString=rString.replace(".00","")),currencySymbol=$("StoreData").attr("CurrencySymbol"),currencyCode=$("StoreData").attr("CurrencyCode"),prependCurrencySymbol&&(rString=currencySymbol+rString),appendCurrencyCode&&currencySymbol=="$"&&currencyCode.toUpperCase()!="USD"&&(rString+=" "+currencyCode),rString},Format.FormatDate=function(d){var rVal="",tString=new String(""),month=d.getMonth()+1,day=d.getDate(),year=d.getFullYear(),testDate=new Date("1/1/1901");try{d.getTime()>testDate.getTime()&&(rVal=Format.FixDigits(month,2)+"/"+Format.FixDigits(day,2)+"/"+year)}catch(ex){}return rVal},Format.FormatTime=function(d){var tString=new String(""),pm=!1,hours=d.getHours(),minutes=d.getMinutes(),seconds=d.getSeconds();return hours>11&&(hours-=12,pm=!0),hours==0&&(hours=12),Format.FixDigits(hours,2)+":"+Format.FixDigits(minutes,2)+" "+(pm?"PM":"AM")},Format.FormatDateTime=function(d){var rVal="";return Format.FormatDate(d)!=""&&Format.FormatDate(d)!="1/1/1900"&&Format.FormatDate(d)!=""&&(rVal=Format.FormatDate(d)+" "+Format.FormatTime(d)),rVal},Format.FormatRtSafe=function(inString){var rVal=""+inString,oVal=rVal;rVal=rVal.replace(/\& /gi,"&amp; ");rVal=rVal.replace(/\'/gi,"&#39;");rVal=rVal.replace(/’/gi,"&#39;");rVal=rVal.replace(/“/gi,"&quot;");rVal=rVal.replace(/”/gi,"&quot;");rVal=rVal.replace(/< /gi,"&lt; ");rVal=rVal.replace(/ >/gi," &gt;");for(var index=-1,nextLtIndex=-1,nextGtIndex=-1,nextSpaceIndex=-1,prevLtIndex=-1,prevGtIndex=-1,prevSpaceIndex=-1,keepGoing=!0,isPartOfTag;keepGoing;)isPartOfTag=!1,index=rVal.indexOf("<",index+1),index<0?keepGoing=!1:(nextLtIndex=rVal.indexOf("<",index+1),nextGtIndex=rVal.indexOf(">",index+1),nextSpaceIndex=rVal.indexOf(" ",index+1),nextGtIndex<index||nextLtIndex>index&&nextLtIndex<nextGtIndex||nextSpaceIndex>index&&nextSpaceIndex<nextGtIndex&&rVal[nextGtIndex-1]!='"'&&rVal[nextGtIndex-1]!="/"&&!(rVal[index+1]=="!"&&rVal[index+2]=="-"&&rVal[index+3]=="-")||(isPartOfTag=!0),isPartOfTag||(rVal=rVal.substring(0,index-1)+"&lt;"+rVal.substring(index+1)),index++);for(index=rVal.length,keepGoing=!0;keepGoing;)isPartOfTag=!1,index=rVal.lastIndexOf(">",index-1),index<0?keepGoing=!1:(prevLtIndex=rVal.substring(0,index-1).lastIndexOf("<"),prevGtIndex=rVal.substring(0,index-1).lastIndexOf(">"),prevSpaceIndex=rVal.substring(0,index-1).lastIndexOf(" "),prevLtIndex<0||prevGtIndex>=0&&prevLtIndex<prevGtIndex||prevSpaceIndex>=0&&prevSpaceIndex>prevLtIndex&&rVal[index-1]!='"'&&rVal[index-1]!="/"&&!(rVal[index-1]=="-"&&rVal[index-2]=="-")||(isPartOfTag=!0),isPartOfTag||(rVal=rVal.substring(0,index-1)+"&gt;"+rVal.substring(index+1)),index--);return(rVal.indexOf("<p>")<0||rVal.lastIndexOf("<p")==rVal.indexOf("<p"))&&(rVal=rVal.replace(/\"/gi,"&quot;"),rVal=rVal.replace(/\r\n/gi,"<br>"),rVal=rVal.replace(/\r/gi,"<br>"),rVal=rVal.replace(/\n/gi,"<br>")),rVal},Format.GetSelectOptionsString=function(objarray,valField,textField,addAllOption,removeBlankOption,selectedValue){var buf,i;if(addAllOption===void 0&&(addAllOption=!1),removeBlankOption===void 0&&(removeBlankOption=!1),selectedValue===void 0&&(selectedValue=""),buf=new StringBuffer,addAllOption&&buf.append('<option value="All">All<\/option>'),objarray!=null)for(i=0;i<objarray.length;i++)eval("objarray[i]."+textField)==""&&removeBlankOption||(buf.append('<option value="'+eval("objarray[i]."+valField)+'"'),eval("objarray[i]."+valField)==selectedValue&&buf.append(" selected"),buf.append(">"+eval("objarray[i]."+textField)+"<\/option>"));return buf.toString()},Format.GetSelectOptionsStringFromSimpleArray=function(objarray,addAllOption,removeBlankOption){var buf,i;for(addAllOption===void 0&&(addAllOption=!1),removeBlankOption===void 0&&(removeBlankOption=!1),buf=new StringBuffer,addAllOption&&buf.append('<option value="All">All<\/option>'),i=0;i<objarray.length;i++)eval("objarray[i]")==""&&removeBlankOption||buf.append('<option value="'+eval("objarray[i]")+'">'+eval("objarray[i]")+"<\/option>");return buf.toString()},Format.GetProductOptionString=function(size,selected){var optionTemplate='<option value="{{id}}" {{selected}} {{disabled}}>{{size}} - {{price}} {{instock}}<\/option>';return optionTemplate=optionTemplate.replace("{{id}}",size.ID),optionTemplate=optionTemplate.replace("{{selected}}",selected===!0?"selected":""),optionTemplate=optionTemplate.replace("{{size}}",size.Name),optionTemplate=optionTemplate.replace("{{price}}",Format.FormatCurrencyWithCommas(size.UnitPrice,!1,!0,!1)),optionTemplate=optionTemplate.replace("{{instock}}",size.InStock===!0?"":"- Out of Stock"),optionTemplate.replace("{{disabled}}",size.InStock===!0?"":"disabled")},Format}();ZUtility.Format=Format;StringBuffer=function(){function StringBuffer(){this.buffer=[]}return StringBuffer.prototype.append=function(val){return this.buffer.push(val),this},StringBuffer.prototype.toString=function(){return this.buffer.join("")},StringBuffer}();ZUtility.StringBuffer=StringBuffer;Array=function(){function Array(){}return Array.SortObjectArray=function(list,sortfield){for(var j,rVal=list,tVal,i=0;i<rVal.length-1;i++)for(j=i+1;j<rVal.length;j++)eval("rVal[i]."+sortfield)>eval("rVal[j]."+sortfield)&&(tVal=rVal[j],rVal[j]=rVal[i],rVal[i]=tVal);return rVal},Array.AddToObjectArray=function(array1,array2,sortfield){for(var rVal=[],i=0,j=0,z=0,tArray=null;i<array1.length&&j<array2.length;)eval("array1[i]."+sortfield)<eval("array2[j]."+sortfield)?(rVal.push(array1[i]),i++):(rVal.push(array2[j]),j++);for(i<array1.length?(tArray=array1,z=i):(tArray=array2,z=j);z<tArray.length;)rVal.push(tArray[z]),z++;return rVal},Array.RemoveFromObjectArray=function(array1,array2,valfield){for(var j,rVal=[],exists=!1,i=0;i<array1.length;i++){for(exists=!1,j=0;j<array2.length;j++)if(eval("array1[i]."+valfield)==eval("array2[j]."+valfield)){exists=!0;break}exists||rVal.push(array1[i])}return rVal},Array}();ZUtility.Array=Array;ClientXml=function(){function ClientXml(){}return ClientXml.StripOuterTags=function(instring){var xml=instring,i;for(xml.indexOf(">")>0&&(xml=xml.substring(xml.indexOf(">")+1)),i=xml.length-1;i>=0;i--)if(xml[i]=="<"){xml=xml.substring(0,i);break}return xml},ClientXml.GetChildXmlElements=function(xml){var rVal=[],tx=ClientXml.GetOuterXmlElementContent(xml),te,i=0,verbose=!1;for(verbose&&alert("tx: "+tx),te=ClientXml.GetFirstXmlElement(tx),verbose&&alert("te: "+te);te!="";)rVal.push(te),tx=tx.replace(te,""),verbose&&alert("tx: "+tx),te=ClientXml.GetFirstXmlElement(tx),verbose&&alert("te: "+te),i++;return rVal},ClientXml.GetFirstXmlElement=function(xml){var tagName="",openCount=0,closeCount=0,tagIsEmpty=!1,indexOfStartTag=xml.indexOf("<"),indexOfEmptyCloseTag=xml.indexOf("/>",indexOfStartTag+1),indexOfFullCloseTag=-1,indexOfNextSlash=xml.indexOf("/",indexOfStartTag+1),indexOfNextSpace=xml.indexOf(" ",indexOfStartTag+1),indexOfNextCloseBracket=xml.indexOf(">",indexOfStartTag+1),indexOfNextOpenBracket=xml.indexOf("<",indexOfStartTag+1),indexOfTagNameEnd=xml.length,indexOfMatchingCloseTag=-1,tx,i;if(indexOfNextSlash>=0&&indexOfNextSlash<indexOfTagNameEnd&&(indexOfTagNameEnd=indexOfNextSlash),indexOfNextSpace>=0&&indexOfNextSpace<indexOfTagNameEnd&&(indexOfTagNameEnd=indexOfNextSpace),indexOfNextCloseBracket>=0&&indexOfNextCloseBracket<indexOfTagNameEnd&&(indexOfTagNameEnd=indexOfNextCloseBracket),indexOfNextOpenBracket>indexOfStartTag+1&&indexOfNextOpenBracket<indexOfEmptyCloseTag&&(indexOfEmptyCloseTag=-1),tagName=xml.substring(indexOfStartTag+1,indexOfTagNameEnd),indexOfFullCloseTag=xml.indexOf("<\/"+tagName+">",indexOfTagNameEnd),(indexOfFullCloseTag<0||indexOfEmptyCloseTag>=0&&indexOfEmptyCloseTag<indexOfFullCloseTag)&&(tagIsEmpty=!0),!tagIsEmpty)for(openCount=1,i=xml.indexOf(">",indexOfStartTag+1)+1;i<xml.length&&indexOfMatchingCloseTag<0;i++)if(tx=xml.substring(i),tx.indexOf("<"+tagName)==0?tx.indexOf("/>",1)>=0&&(tx.indexOf("<",1)<0||tx.indexOf("/>",1)<tx.indexOf("<",1))||openCount++:(tx.indexOf("<\/"+tagName)==0||tx.indexOf("<\/ "+tagName)==0)&&closeCount++,closeCount==openCount){indexOfMatchingCloseTag=i;break}return tagIsEmpty||indexOfMatchingCloseTag<0?xml.substring(indexOfStartTag,indexOfEmptyCloseTag+2):xml.substring(indexOfStartTag,xml.indexOf(">",indexOfMatchingCloseTag)+1)},ClientXml.GetFirstXmlElementTagName=function(xml){var indexOfStartTag=xml.indexOf("<"),indexOfEmptyCloseTag=xml.indexOf("/>",indexOfStartTag+1),indexOfNextSlash=xml.indexOf("/",indexOfStartTag+1),indexOfNextSpace=xml.indexOf(" ",indexOfStartTag+1),indexOfNextCloseBracket=xml.indexOf(">",indexOfStartTag+1),indexOfNextOpenBracket=xml.indexOf("<",indexOfStartTag+1),indexOfTagNameEnd=xml.length;return indexOfNextSlash>=0&&indexOfNextSlash<indexOfTagNameEnd&&(indexOfTagNameEnd=indexOfNextSlash),indexOfNextSpace>=0&&indexOfNextSpace<indexOfTagNameEnd&&(indexOfTagNameEnd=indexOfNextSpace),indexOfNextCloseBracket>=0&&indexOfNextCloseBracket<indexOfTagNameEnd&&(indexOfTagNameEnd=indexOfNextCloseBracket),indexOfNextOpenBracket<indexOfEmptyCloseTag&&(indexOfEmptyCloseTag=-1),xml.substring(indexOfStartTag+1,indexOfTagNameEnd)},ClientXml.GetOuterXmlElementContent=function(xml){var tagName=ClientXml.GetFirstXmlElementTagName(xml);return ClientXml.GetXmlElementContent(tagName,xml)},ClientXml.GetXmlElement=function(tagname,xml){var rVal=xml,tagIsEmpty=!1,indexOfStartTag=-1,indexOfCloseTag=-1,indexOfEmptyClose=-1,indexOfContentAfterStartTag=-1,i;if(rVal.indexOf("<"+tagname)>=0&&rVal.indexOf(">")>0)if(indexOfStartTag=rVal.indexOf("<"+tagname),indexOfStartTag>=0&&(indexOfEmptyClose=rVal.indexOf("/>",indexOfStartTag+tagname.length),indexOfContentAfterStartTag=rVal.indexOf(">",indexOfStartTag)+1),(indexOfContentAfterStartTag<1||indexOfEmptyClose>indexOfStartTag&&indexOfEmptyClose<indexOfContentAfterStartTag)&&(tagIsEmpty=!0),tagIsEmpty)rVal=rVal.substring(indexOfStartTag),rVal=rVal.substring(0,rVal.indexOf("/>")+2);else{for(rVal=rVal.substring(indexOfStartTag),i=rVal.length-tagname.length;indexOfCloseTag<0&&i>=0;i--)if(rVal.substring(i).indexOf("<\/"+tagname+">")==0){indexOfCloseTag=i;break}indexOfCloseTag>=0&&(rVal=rVal.substring(0,indexOfCloseTag+tagname.length+3))}return rVal},ClientXml.GetXmlElementContent=function(tagname,xml){var rVal=xml,tagIsEmpty=!1,indexOfStartTag=rVal.indexOf("<"+tagname),indexOfCloseTag=-1,indexOfEmptyClose=-1,indexOfContentAfterStartTag=-1,i;if(indexOfStartTag>=0&&rVal.indexOf(">",indexOfStartTag+1)>0)if(indexOfEmptyClose=rVal.indexOf("/>",indexOfStartTag+tagname.length),indexOfContentAfterStartTag=rVal.indexOf(">",indexOfStartTag+tagname.length)+1,(indexOfContentAfterStartTag<1||indexOfEmptyClose>indexOfStartTag&&indexOfEmptyClose<indexOfContentAfterStartTag)&&(tagIsEmpty=!0),tagIsEmpty)rVal="";else{for(rVal=rVal.substring(indexOfContentAfterStartTag),i=rVal.length-tagname.length;indexOfCloseTag<0&&i>=0;i--)if(rVal.substring(i).indexOf("<\/"+tagname+">")==0){indexOfCloseTag=i;break}indexOfCloseTag>=0&&(rVal=rVal.substring(0,indexOfCloseTag))}return rVal},ClientXml.GetXmlElementAttributes=function(xml,tagname){var rVal={},xmlAttributesRaw=[],tAttrStringArray,xmlElements=[],rootElementName,myEl,eXml,endIndex,i;for(rootElementName=tagname!=null&&tagname!=""?tagname:ClientXml.GetFirstXmlElementTagName(xml),myEl=ClientXml.GetXmlElement(rootElementName,xml),xmlElements=ClientXml.GetChildXmlElements(myEl),eXml=myEl.replace(/\\\"/g,"&quot;"),xmlElements.length>0?eXml.indexOf("<"+rootElementName+">")>0?xmlAttributesRaw=[]:(eXml=eXml.replace("<"+rootElementName,""),eXml=eXml.substring(1,eXml.indexOf('">')),xmlAttributesRaw=eXml.split('" ')):(endIndex=eXml.indexOf('"/>'),endIndex<1&&(endIndex=eXml.indexOf('" />')),eXml=eXml.replace("<"+rootElementName,""),eXml=eXml.substring(1,endIndex),xmlAttributesRaw=eXml.split('" ')),i=0;i<xmlAttributesRaw.length;i++)tAttrStringArray=xmlAttributesRaw[i].split('="'),rVal[tAttrStringArray[0]]=tAttrStringArray[1];return rVal},ClientXml}();ZUtility.ClientXml=ClientXml;XmlParsedPackage=function(){function XmlParsedPackage(elementname,titleattribute,xml){var xColumns=[],xTags=[],xData=[],isEmpty,txRow="",xmlElements=ClientXml.GetChildXmlElements(xml),tElements,xContent="",i,j;if(this.Attributes=ClientXml.GetXmlElementAttributes(xml),xmlElements.length>0)for(tElements=ClientXml.GetChildXmlElements(xmlElements[0]),j=0;j<tElements.length;j++)xTags[j]=ClientXml.GetFirstXmlElementTagName(tElements[j]),xContent=ClientXml.GetOuterXmlElementContent(tElements[j]),isEmpty=xContent=="",txRow=tElements[j],xColumns[j]=ClientXml.GetFirstXmlElementTagName(txRow);for(i=0;i<xmlElements.length;i++)for(tElements=ClientXml.GetChildXmlElements(xmlElements[i]),xData[i]=[],j=0;j<tElements.length;j++)xContent=ClientXml.GetOuterXmlElementContent(tElements[j]),xData[i][xColumns[j]]=xContent;this.Tags=xTags;this.Columns=xColumns;this.Data=xData;this.Xml=xml;this.ElementName=elementname;this.TitleAttribute=titleattribute}return XmlParsedPackage}();ZUtility.XmlParsedPackage=XmlParsedPackage}(ZUtility||(ZUtility={}))